###前提・実現したいこと
コレクションビューのヘッダーに、テーブルビューのセクションタイトルのように、それぞれタイトルを表示させたくて、以下のobjective-Cのコードを自分なりにswift3に書き直しました。
Objective
1- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView 2 viewForSupplementaryElementOfKind:(NSString *)kind 3 atIndexPath:(NSIndexPath *)indexPath { 4 UICollectionReusableView* reusableview = nil; 5 6 if (kind == UICollectionElementKindSectionHeader) { 7 // --- ヘッダ 8 UICollectionReusableView* headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader 9 withReuseIdentifier:@"HeaderView" 10 forIndexPath:indexPath]; 11 UILabel *label = [headerView viewWithTag:1]; 12 label.text = titles[indexPath.section]; 13 14 reusableview = headerView; 15 } 16 return reusableview; 17}
↓こうしました↓
swift
1 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 2 var reusableView = nil //エラー1 3 if kind == UICollectionElementKindSectionHeader { 4 let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) 5 let label = headerView.viewWithTag(1) 6 label.text = self.sectionData[section].title //エラー2 7 reusableView = headerView 8 } 9 return headerView //エラー3 10 }
###発生している問題・エラーメッセージ
var reusableView = nil //エラー1 <'nil' requires a contextual type //省略 label.text = self.sectionData[section].title //エラー2 <Value of type 'UIView?' has no member 'text' //省略 return headerView //エラー3 <Use of unresolved identifier 'headerView'
とりあえず、let headerViewの部分がうまくはまっていないみたいなのはわかるのですが・・・
エラー1についてのヘッダーのリユースについての使い方もよくわかっていません・・・
ちなみに、StoryBoard上でCollectionReusableViewのidentifierを"HeaderView"にして、
その中に配置したラベルのタグは1にしてあります。
###試したこと
わたしにわかったのは、何かしらreusableに特別な指定方法がありそうということ、headerViewが何者かをswiftが理解していないこと、そのせいでheaderViewのtag1がラベルだと気がついてもらえていないことくらいでした・・・
###補足情報(言語/FW/ツール等のバージョンなど)
xcode8 swift3
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/18 11:51