LoginSignup
7
8

More than 5 years have passed since last update.

[iOS8] SwiftでUIScrollViewを利用して画像をスライド・スクロールさせる

Posted at

swift上で画像を上下・左右にスライド・スクロールさせたい時の実装をサンプルコードをみながら説明していきます。
以下、2パターンを例に見ていこうと思います。

【パターン】
①画像を上下左右にスライドする
②画像を上下左右にスクロールする

【フレームワーク】
UIScrollView, UIImageView, UIImage

【事前準備】
画像:img1.png, img2.png, img3.pngの3枚を利用しています。

【サンプルコード】
https://github.com/eversense-maezawa/Swift-UIScrollView-Example

1. スライド

1.1 左右にスライドさせる


実装結果とサンプルコードになります。
scroll2
        
        //UIImageに画像の名前を指定します
        let img1 = UIImage(named:"img1.jpg");
        let img2 = UIImage(named:"img2.jpg");
        let img3 = UIImage(named:"img3.jpg");
        
        //UIImageViewにUIIimageを追加
        let imageView1 = UIImageView(image:img1)
        let imageView2 = UIImageView(image:img2)
        let imageView3 = UIImageView(image:img3)

        //UIScrollViewを作成します
        let scrView = UIScrollView()

        //UIScrollViewの1ページ分のサイズ + 表示位置 
        scrView.frame = CGRectMake(0, 0, 240, 240)

        //全体のサイズ
        scrView.contentSize = CGSizeMake(240, 240*3)
        
        //UIImageViewのサイズと位置を決めます
        imageView1.frame = CGRectMake(0, 0, 240, 240)
        imageView2.frame = CGRectMake(240, 0, 240, 240)
        imageView3.frame = CGRectMake(480, 0, 240, 240)

        //viewに追加します
        self.view.addSubview(scrView)

        //UIImageViewをScrollViewに追加します
        scrView.addSubview(imageView1)
        scrView.addSubview(imageView2)
        scrView.addSubview(imageView3)

        // 1ページ単位でスクロールさせる
        scrView.pagingEnabled = true

ポイントとなるのは、以下3点のサイズになります。
( UIScrollView全体 ) >=( UIScrollView × ページ数 )>=( UIImageView × ページ数 )
基本的に、スクロール可能領域を超えたサイズの画像をスクロールさせることは挙動がおかしくなるのでやめましょう。

1.2 上下にスライドさせる


1.1のサンプルコードを変更します。
UIImageViewと、UIScrollViewのx座標とy座標を入れ替えます。

Scroll-UpDown-PageEnable-YES


    //全体のサイズ
    scrView.contentSize = CGSizeMake(240*3, 240)  //変更箇所

    //UIImageViewのサイズと位置を決めます
    imageView1.frame = CGRectMake(0, 0, 240, 240)
    imageView2.frame = CGRectMake(0, 240, 240, 240)  //変更箇所
    imageView3.frame = CGRectMake(0, 480, 240, 240)  //変更箇所



 

2. スクロール

2.1 左右にスクロールさせる


1.1からのソースコードの変更点は1箇所です。

scroll


     //scrView.pagingEnabled = true  //コメントアウト
     scrView.pagingEnabled = false   //もしくはfalseを返す

2.2 上下にスクロールさせる


1.2からの変更点は上記と同様です。

Scroll-UpDown-PageEnable-NO

【サンプルコード】
https://github.com/eversense-maezawa/Swift-UIScrollView-Example

以上、swiftでUIScrollViewを利用して画像をスライド・スクロールさせる方法は終了です。
ありがとうございました。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8