###前提・実現したいこと
コレクションビューのUICollectionReusableViewに、func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
メソッドを使って、各ヘッダーセクションにタイトル情報を渡したくて、以下のようにコードを書きました。
swfit
1var sectionTitle = ["その1", "その2", "その3", "その4", "その5", "その6", "その7"] 2//省略 3func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 4 var reusableView = UICollectionReusableView() 5 if kind == UICollectionElementKindSectionHeader { 6 let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) 7 if let label = headerView.viewWithTag(1) as? UILabel { 8 label.text = self.sectionTitle[/*ここがわからないです*/] 9 } 10 reusableView = headerView 11 } 12 return reusableView 13 }
###発生している問題・エラーメッセージ
sectionTitle配列から順番に取り出したいので、
swift
1var sectionIndex = 0 2//省略 3if let label = headerView.viewWithTag(1) as? UILabel { 4 label.text = self.sectionTitle[/*ここがわからないです*/] 5 } 6 reusableView = headerView 7 sectionIndex += 1 8 }
としてみたのですが、
これだとセクションヘッダーがリユースされるたびに(reusableViewが画面に表示されるたびに)、sectionIndex
が+1されてしまい、「その1」と表示されていた部分に「その2」、「その3」と表示されてしまいます。
テーブルビューの場合、
swift
1func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 2 self.sectionTitle[section] 3}
で取り出せると思うのですが、コレクションビューの場合、引数にsection
というInt型の引数がないため、オリジナルで回そうとして失敗したという形です・・・。
###補足情報(言語/FW/ツール等のバージョンなど)
swift3 xcode8
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/28 12:49