現在もSwiftを勉強しているものです。
早速ですが表題の件について質問があります。
CollectionViewを使用して、
セルを選択した場合に色を変えるという事を勉強していました。
こちらは分かったのですが、
逆に選択されていないセルの色を変更など出来ないものかと考えております。
どうしても方法を思いつきませんでしたので、
こちらに投稿させて頂きました。
こちらのサイト様を参考に勉強して
タップしたら色を変えるだけを実装しております。
Swift
1// ViewController 2 3import UIKit 4 5class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { 6 7 var myCollectionView : UICollectionView! 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 12 // CollectionViewのレイアウトを生成. 13 let layout = UICollectionViewFlowLayout() 14 15 16 // Cell一つ一つの大きさ. 17 layout.itemSize = CGSize(width:50, height:50) 18 19 // Cellのマージン. 20 layout.sectionInset = UIEdgeInsetsMake(16, 16, 32, 16) 21 22 // セクション毎のヘッダーサイズ. 23 layout.headerReferenceSize = CGSize(width:100,height:30) 24 25 // CollectionViewを生成. 26 myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) 27 28 // Cellに使われるクラスを登録. 29 myCollectionView.register(CustomUICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell") 30 31 myCollectionView.delegate = self 32 myCollectionView.dataSource = self 33 34 self.view.addSubview(myCollectionView) 35 36 } 37 38 /* 39 Cellが選択された際に呼び出される 40 */ 41 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 42 43 print("Num: \(indexPath.row)") 44 45 let cell = collectionView.cellForItem(at: indexPath) as! CustomUICollectionViewCell 46 // 選択されたセルを赤にする 47 cell.imageView.backgroundColor = .red 48 } 49 50 /* 51 Cellの総数を返す 52 */ 53 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 54 return 8 55 } 56 57 /* 58 Cellに値を設定する 59 */ 60 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 61 62 let cell : CustomUICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomUICollectionViewCell 63 64 return cell 65 } 66 67}
Swift
1// CustomCell 2 3import UIKit 4 5class CustomUICollectionViewCell : UICollectionViewCell{ 6 7 var imageView: UIImageView! 8 9 required init(coder aDecoder: NSCoder) { 10 super.init(coder: aDecoder)! 11 } 12 13 override init(frame: CGRect) { 14 super.init(frame: frame) 15 16 // UILabelを生成. 17 imageView = UIImageView(frame: CGRect(x:0, y:0, width:frame.width, height:frame.height)) 18 imageView.backgroundColor = UIColor.white 19 20 // Cellに追加. 21 self.contentView.addSubview(imageView) 22 } 23 24}
実装したい内容を詳しく説明すると、
セル0をタップして赤に変更する
→セル1をタップしてセル1を赤に変更、セル0を白に戻す
→セル2をタップしてセル2を赤に変更、セル1を白に戻す
→・・・・
というように常に1つのセルの色だけを変更したいです。
どうかご教授お願い致します。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/11/22 01:51
2016/11/22 01:57
2016/11/22 02:21