前提・実現したいこと
初学者です。周りに頼れる人もおらず初めて投稿させていただきました。
collection viewのセルをタップ(選択)した時に、セルの番号を、画面上部のラベル(resultLabel)に表示させたいです。
発生している問題・エラーメッセージ
実際にセルをタップしても、下記のソースコードの関数 collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) が呼び出されません。
該当のソースコード
// // View2ViewController.swift // insuubunkai // // Created by 山田 on 2019/08/01. // Copyright © 2019 山田. All rights reserved. // import UIKit class View2ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var CollectionView1: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 12 // 表示するセルの数 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "Cell", for: indexPath) // 表示するセルを登録(先程命名した"Cell") //セルの背景色をランダムに設定する。 cell.backgroundColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0) let cellButton1 = cell.contentView.viewWithTag(1) as! UIButton cellButton1.setTitle(String(indexPath.row + 1), for: .normal) cellButton1.setTitleColor(UIColor.white, for: .normal) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { resultLabel.text = String(indexPath.row) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
試したこと
resultLabel.text = String(indexPath.row)
の代わりに
print("関数が呼び出されました")
等に書き換えても、デバッグエリアでの出力は確認出来ませんでした。
下記のサイト等を参考にしております。
・https://i-app-tec.com/ios/collectionview-cellselect.html
・http://simple-life777.hatenablog.com/entry/2019/01/22/CollectionView%E3%81%AE%E4%BD%BF%E3%81%84%E6%96%B9
補足情報(FW/ツールのバージョンなど)
XcodeのバージョンはVersion 10.2.1 (10E1001)です。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/10 11:39
2019/08/10 11:41
2019/08/10 13:00
2019/08/10 13:15
2019/08/10 13:50