UICollectionViewで横scrollする方法 – Swift3

皆さんこんにちわ

将来は日本を脱出して海外移住起業や!!!を企む凡人、Hujisawaでございます〜^^

よろしくね。

さてさて

本日はSwiftでございます。

UICollectionViewを使って横スクロールを実装してみたいと思います。

実行が下記のようになります。

cole.gif

実装

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var myCollectionView : UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // CollectionViewのレイアウトを生成.
        let layout = UICollectionViewFlowLayout()


        // Cell一つ一つの大きさ.
        layout.itemSize = CGSize(width:50, height:50)

        // Cellのマージン.
        layout.sectionInset = UIEdgeInsetsMake(16, 16, 32, 16)

        // セクション毎のヘッダーサイズ.
        //layout.headerReferenceSize = CGSize(width:100,height:30)

        layout.scrollDirection = .horizontal

        // CollectionViewを生成.
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        // Screen Size の取得
        let screenWidth:CGFloat = view.frame.size.width
        let screenHeight:CGFloat = view.frame.size.height

        myCollectionView.frame = CGRect(x:0, y:screenHeight/2, width:screenWidth, height:50)

        // Cellに使われるクラスを登録.
        myCollectionView.register(CustomUICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")

        myCollectionView.backgroundColor = UIColor.clear

        myCollectionView.delegate = self
        myCollectionView.dataSource = self

        self.view.addSubview(myCollectionView)

}

    /*
     Cellが選択された際に呼び出される
     */
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("Num: \(indexPath.row)")

    }

    /*
     Cellの総数を返す
     */
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
}

    /*
     Cellに値を設定する
     */
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell : CustomUICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomUICollectionViewCell
        cell.textLabel?.text = indexPath.row.description

        return cell
    }

}

セルのためのカスタムクラス

import UIKit

class CustomUICollectionViewCell: UICollectionViewCell {

    var textLabel : UILabel?

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        // UILabelを生成.
        textLabel = UILabel(frame: CGRect(x:0, y:0, width:frame.width, height:frame.height))
        textLabel?.text = "nil"
        textLabel?.backgroundColor = UIColor.white
        textLabel?.textAlignment = NSTextAlignment.center

        // Cellに追加.
        self.contentView.addSubview(textLabel!)
    }

}

参照

TECHNICAL MASTER はじめてのiOSアプリ開発 第2版 Xcode 8+Swift 3対応【電子書籍】[ 長谷川智希 ]

github

UITableViewに追加・削除機能を追加

Swift3 UICollectionViewで横スクロール

宣伝

Twitterやってるよ^^

YouTubeもやってるよ

よければフォローしてくれたらフォロバする〜

SEOとかウェブ開発得意ですーー

お気軽に絡んでください〜

自主開発サービス

https://www.language-exchange.fun/

https://www.language-exchange.fun/

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

未整理記事