UICollectionViewControllerを継承したらハマった
[File] – [[New] – [File…]から、Cocoa Touch Classを選んで、
Subclass of:にUICollectionViewControllerを設定してファイルを生成したら、
どハマりした。
この手順は、
ありがちなコードが記述された状態でファイルが追加されるので良く使ってるんだけど、
理解していない処理をそのまま放置しておくと、思わぬところでハマる。
それがこれ。
let reuseIdentifier = "Cell"
class MyCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
/* ↓ これね! */
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
UICollectionViewが目的の機能に合っているか確認したくて、
とりあえず表示してみようと思ってStoryboard上でセルをいじっても反映されなくて、
「あれれ???」ってなったまま1日を過ごした。
そもそも、Storyboard上でUICollectionViewCellの見た目を変えて、
それを使用するのにIdentifierに”Cell”を設定して、
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
// Configure the cell
return cell
}
こんな感じで使用している。
もしStoryboard上で、
UICollectionViewにあるUICollectionViewCellを使わないなら、
UICollectionViewCellを継承したclassを定義して、
UICollectionView#registerClassを使って、紐付けに相当する処理を行う。
この場合は、init(frame: CGRect)が呼ばれるので、
この中でUIViewとか、その手の処理を行う。
で、結局うまく動作しなかった理由は、せっかくStoryboard上で定義した設定を、
UICollectionView#registerClassによって上書きしたせいで、
Appleの公式サイトからちゃんと動くサンプルコードを落としてきて、
それと比較することで解決することができた。
めでたし、めでたし。
Leave a Comment