現在iosアプリを作っているのですが、表題のようにcollectionViewCellで、xib生成されたあとに呼び出されるメソッドを教えていただきたいです。
やりたいこととしては、collectionViewのcellForItemAtメソッドからcell内の変数に値を渡して、その値をcellのラベルに表示するということなのですが、下記のようにcell内の変数のdidSetで処理を行うと、labelがnilの状態なのでエラーとなってしまいます。
swift
1//セルの処理 2class MenuBarViewCell: UICollectionViewCell { 3 @IBOutlet var label: UILabel! 4 var isCompletedSetUpUI: Bool = false 5 var title:String!{ 6 didSet{ 7 label.text = title 8 } 9 } 10}
swift
1//collectionViewの処理 2class MenuBarView: UIView { 3 var pageTabItemsWidth: CGFloat = 0.0 4 var collectionView:UICollectionView! 5 var titles: [String] = Constant.menuTitle 6 override init(frame: CGRect) { 7 super.init(frame: frame) 8 setUpCollectionView() 9 } 10 11 required init?(coder aDecoder: NSCoder) { 12 fatalError("init(coder:) has not been implemented") 13 } 14} 15 16extension MenuBarView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 17 fileprivate func setUpCollectionView(){ 18 let layout = UICollectionViewFlowLayout() 19 layout.itemSize = CGSize(width:100, height:30) 20 layout.scrollDirection = .horizontal 21 collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height), collectionViewLayout: layout) 22 // Cellに使われるクラスを登録. 23 collectionView.delegate = self 24 collectionView.dataSource = self 25 collectionView.showsHorizontalScrollIndicator = false 26 collectionView.register(MenuBarViewCell.self, forCellWithReuseIdentifier: "MyCell") 27 self.addSubview(collectionView) 28 29 } 30 31 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 32 return titles.count * 3 33 } 34 35 /* 36 Cellに値を設定する 37 */ 38 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 39 let cell : MenuBarViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell",for: indexPath) as! MenuBarViewCell 40 configureCell(cell: cell, indexPath: indexPath) 41 return cell 42 } 43 44 private func configureCell(cell:MenuBarViewCell, indexPath: IndexPath){ 45 let fixedIndex = indexPath.item % titles.count 46 cell.title = titles[fixedIndex] 47 } 48} 49 50extension MenuBarView: UIScrollViewDelegate { 51 func scrollViewDidScroll(_ scrollView: UIScrollView) { 52 if pageTabItemsWidth == 0.0 { 53 pageTabItemsWidth = floor(scrollView.contentSize.width / 3.0) // 表示したい要素群のwidthを計算 54 } 55 56 if (scrollView.contentOffset.x <= 0.0) || (scrollView.contentOffset.x > pageTabItemsWidth * 2.0) { // スクロールした位置がしきい値を超えたら中央に戻す 57 scrollView.contentOffset.x = pageTabItemsWidth 58 } 59 } 60} 61
イニシャライザで行っても同様です。
どなたかご回答いただけると助かります。
回答1件
あなたの回答
tips
プレビュー