前提・実現したいこと
CollectionViewDelegateでindexPath(for: cell)を使ってセルのindexPathを取得したいのですが、
なぜかnilが帰ってきてしまいます
どうすればいいのか、ご存知の方教えていただけませんでしょうか?
よろしくお願いいたします
発生している問題・エラーメッセージ
nilになってしまう
試したこと
swift
1class ViewController: UIViewController { 2 3 @IBOutlet weak var testCollection: UICollectionView! 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 testCollection.dataSource = self 8 testCollection.delegate = self 9 testCollection.register(UINib.init(nibName: "TestCollectionCell", bundle: nil), forCellWithReuseIdentifier: "TestView") 10 // Do any additional setup after loading the view, typically from a nib. 11 } 12} 13 14extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource{ 15 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 16 return 5 17 } 18 19 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 20 let cell = testCollection.dequeueReusableCell(withReuseIdentifier: "TestView", for: indexPath) as! TestCollectionCell 21 indexSet(cell: cell) 22 return cell 23 } 24 25 private func indexSet(cell: TestCollectionCell){ 26 //ここでindexPathを取得したいが、nilになってしまう 27 let index = self.testCollection.indexPath(for: cell) 28 cell.testText.text = String(describing: index?.row) 29 } 30 31}
補足情報(FW/ツールのバージョンなど)
Swift 4.2
Xcode 10.1
回答1件
あなたの回答
tips
プレビュー