#達成したいこと
ViewControllerを開いた際に、UICollectionView内の一番初めのセルが選択されている状態にしたい。
#試したこと
以下のコードを記述。
swift
1 override func viewWillAppear(_ animated: Bool) { 2 super.viewWillAppear(animated) 3 4 let testIndexpath: IndexPath = IndexPath(row: 0, section: 0) 5 collectionView.selectItem(at: testIndexpath, animated: true, scrollPosition: UICollectionView.ScrollPosition.bottom) 6 }
#現在発生している障害
UIViewControllerを開いた際に、1番初めのセルが選択状態にならない。
なお、viewWillAppearではなく、viewDidLoad, viewDidAppearにも上記コードを記述してみたが結果は同じだった。
原因が分かる方がいたら、ぜひ教えていだけますでしょうか。
#補足
各セルにはUIImageViewをセット。
選択されたセルは、UIImageViewのalphaを1に設定。
選択されていないセルは、UIImageViewのalphaを0.3に設定。
これで選択されているセルが視覚的に分かるようにしている。
コード全体は以下。
※初期状態でUIImageViewのalphaを0.3に設定しているが、それはstoryboardから設定しているためコードには書かれていない。
swift
1import UIKit 2import Foundation 3 4class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 5 6 @IBOutlet weak var collectionView: UICollectionView! 7 let img:[String] = ["a","b","c","d","e","f","g",] 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 } 12 13 override func viewWillAppear(_ animated: Bool) { 14 super.viewWillAppear(animated) 15 16 let testIndexpath: IndexPath = IndexPath(row: 0, section: 0) 17 collectionView.selectItem(at: testIndexpath, animated: true, scrollPosition: UICollectionView.ScrollPosition.bottom) 18 } 19 20 // cellの数を返す関数 21 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 22 return img.count 23 } 24 25 // cellに情報を入れていく関数 26 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 27 // Identifierが"cell"でUICollectionViewCellというクラスのcellを取得 28 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 29 //画像を取得 30 let img = UIImage(named: img[indexPath.row]) 31 32 // Tag番号 1 で UIImageView インスタンスの生成 33 let imageView = cell.viewWithTag(1) as! UIImageView 34 imageView.image = img 35 36 return cell 37 } 38 39 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 40 print("Selected: (indexPath)") 41 42 //タップしたセルを取得 43 let cell = collectionView.cellForItem(at: indexPath)! 44 45 //タップしたセルが持つUIImageViewを取得 46 let selectedImageView = cell.viewWithTag(1) as! UIImageView 47 selectedImageView.alpha = 1 48 } 49 50 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { 51 print("Deselected: (indexPath)") 52 //タップしたセルを取得 53 if let cell = collectionView.cellForItem(at: indexPath) { 54 //タップしたセルが持つUIImageViewを取得 55 let selectedImageView = cell.viewWithTag(1) as! UIImageView 56 selectedImageView.alpha = 0.3 57 } else { 58 print("セルを取得できませんでした") 59 } 60 } 61 62 63} 64
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/29 09:46 編集