Swift3 UIImageをUIScrollViewに追加して横スクロール

ストーリーボードトコードを両立させての実装です。

スクリーンショット 2017-06-17 17.43.46.png

環境

  • xcode8
  • swift3

実行

rapgods.gif

実装


import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    // 画像インスタンス
    var drakeIsTheBestInTheWorld = UIImageView()
    var eminemIsFantastic = UIImageView()
    var lilwayneIsSuperMan = UIImageView()
    var jayzIsfamous = UIImageView()
    var kanyeIskanye = UIImageView()

    @IBOutlet weak var anotherScrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 中身の大きさを設定
        anotherScrollView.contentSize = CGSize(width: 1000, height: 100)
        // スクロールの跳ね返り
        anotherScrollView.bounces = false
        // Delegate を設定
        anotherScrollView.delegate = self

       drakeIsTheBestInTheWorld = UIImageView.init(frame: CGRect.init(x: 0, y:15, width: 100, height: 100))
       drakeIsTheBestInTheWorld.image = UIImage(named: "drake")
       self.anotherScrollView.addSubview(drakeIsTheBestInTheWorld)

        eminemIsFantastic = UIImageView.init(frame: CGRect.init(x: 100, y:15, width: 100, height: 100))
        eminemIsFantastic.image = UIImage(named: "eminem")
        self.anotherScrollView.addSubview(eminemIsFantastic)

        lilwayneIsSuperMan = UIImageView.init(frame: CGRect.init(x: 200, y:15, width: 100, height: 100))
        lilwayneIsSuperMan.image = UIImage(named: "lilwayne")
        self.anotherScrollView.addSubview(lilwayneIsSuperMan)

        jayzIsfamous = UIImageView.init(frame: CGRect.init(x: 300, y:15, width: 100, height: 100))
        jayzIsfamous.image = UIImage(named: "jayz")
        self.anotherScrollView.addSubview(jayzIsfamous)

        kanyeIskanye = UIImageView.init(frame: CGRect.init(x: 400, y:15, width: 100, height: 100))
        kanyeIskanye.image = UIImage(named: "kanye")
        self.anotherScrollView.addSubview(kanyeIskanye)

    }

       override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    /* 以下は UITextFieldDelegate のメソッド */
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // スクロール中の処理
        print("didScroll")
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        // ドラッグ開始時の処理
        print("beginDragging")
    }
}

参考

GitHub

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事