前提・実現したいこと
以下の写真のようなcollectionViewのセルの内容をボタンを押して変更できるようにしたいです。
具体的にはセルを選択している状態で画面下部のButtonを押すと、選択中セル内の”Label”部分が”ラベル”に変わるというようなプログラムを書きたいです。
発生している問題・エラーメッセージ
様々な情報を探して読んでいますが、今回のようなボタンを押してセルの内容を変更するサンプルが見つからず、どうにもならないのが現状です。
全てのセルの”Label”部をボタンで一気に変更することはできましたが、選択しているセルのみを変更しようと色々試していたところ、それも再現できなくなってしまいました。
どうかアドバイス宜しくお願い致します。
該当のソースコード
Swift
import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var indexNum = 0 @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // レイアウトを調整 let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) collectionView.collectionViewLayout = layout } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionViewCell { cell.textLabel.text = String(indexPath.row) cell.textLabel.textColor = .black //タップしたcellの背景色 let selectedBGView = UIView(frame: cell.frame) selectedBGView.backgroundColor = .blue cell.selectedBackgroundView = selectedBGView cell.backgroundColor = .gray // セルの色 return cell } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 18 // 表示するセルの数 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let horizontalSpace : CGFloat = 20 let cellSize : CGFloat = self.view.bounds.width / 3 - horizontalSpace return CGSize(width: cellSize, height: cellSize) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){ indexNum = indexPath.row print(indexNum) } @IBAction func btn1(_ sender: UIButton) { } }
Swift
import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var textLabel: UILabel! // 左上テキスト 数字 @IBOutlet weak var subText: UILabel! // 下テキスト Label override func awakeFromNib() { super.awakeFromNib() } }
まだ回答がついていません
会員登録して回答してみよう