0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

カスタムUICollectionReusableViewをxibで利用する

Last updated at Posted at 2019-06-01

・New File > User Interface の Empty を選択

スクリーンショット 2019-06-01 14.23.58.png

・任意のファイル名を入力
・右上の□を○で囲ったアイコン(Library)ボタンを押下して Collection Reusable View を右側の画面にドラッグ&ドロップ

スクリーンショット 2019-06-01 14.26.55.png

・追加後の画面

スクリーンショット 2019-06-01 14.29.16.png

・今回のサンプルではこれにUILabelを追加したシンプルなヘッダービューを作成します。
・Libraryボタンから同じようにUILabelをReusableViewの中にドラッグ&ドロップ
・最低限のAutoLayoutを設定

スクリーンショット 2019-06-01 14.32.15.png

・右ペインを出して以下のような感じでカスタムクラスを設定

スクリーンショット 2019-06-01 14.33.42.png

・カスタムクラスの内容は以下

CollectionBaseHeaderView.swift

class CollectionBaseHeaderView:UICollectionReusableView{

    @IBOutlet weak var headerLabel: UILabel!
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
}

・ここまでで作成したxibファイルをStoryboardで利用する為に以下の手順を踏みます。

・Storyboard上でCollectionViewをドラッグ&ドロップ
・Libraryボタンから Collection Reusable ViewをCollectionView上にドラッグ&ドロップ
・CustomClassにxibで設定したクラスと同じクラスを設定

スクリーンショット 2019-06-01 14.37.18.png

・CollectionViewを利用するクラスのviewDidLoadで再利用するセルの登録

SampleViewController.swift
override func viewDidLoad() {
        super.viewDidLoad()
        profileCollectionView.register(UINib(nibName: "CollectionBaseHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionBaseHeaderView")
    }

・あとは通常通りにセクションの設定をしていきます。

SampleViewController.swift
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let testSection = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionBaseHeaderView", for: indexPath) as! CollectionBaseHeaderView
        return testSection
    }
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?