私のView Controllerには、レンダリング時に3つのセル(それぞれにラベルとボタンがあります)が表示されるコレクションビューがあります。ラベルには色の名前が表示され、ボタンにはカラースウォッチを表示する背景イメージがあります。ターゲット関数セット(Swift 3)からUICollectionViewのボタンにアクセスする方法
ボタンの1つをクリックするたびに、そのボタンの周りに暗い境界線が表示され、他のボタンが明るい枠線になり、クリックされたボタンが「選択済み」であることがわかります。あるいは、画像の選択された状態に基づいて画像を変更することで、おそらくこれを行うことができますが、私の質問は変わりません。
プロパティを切り替えるには、他の2つのボタンにアクセスするにはどうすればよいですか?
誰かがクリックしたボタンに境界線を追加できるスクリプトが実装されていますが、他のボタンにアクセスする方法を把握することはできません。よくここで
は、(取り除か無関係/無関係なビットで)私のソースコード
class trimSelectorVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var trimSelector: UICollectionView!
struct trimObject {
var trimName: String
var trimButton: String
var trimID: Int
}
var trimArray: [trimObject] = []
override func viewDidLoad() {
super.viewDidLoad()
trimArray.append(trimObject(trimName: "Chrome", trimButton: "chrome-swatch", trimID: 0))
trimArray.append(trimObject(trimName: "Gold", trimButton: "gold-swatch", trimID: 1))
trimArray.append(trimObject(trimName: "Gun Metal", trimButton: "gunmetal-swatch", trimID: 2))
trimSelector.delegate = self
trimSelector.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return trimArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! trimSelectionCell
//Set the label text
cell.trimLabel.text = trimArray[indexPath.item].trimName
//Set the image for the button
cell.trimButton.setImage(UIImage(named: trimArray[indexPath.item].trimButton), for: UIControlState.normal)
//Sets a target function for the button
cell.trimButton.addTarget(self, action: #selector(selectedSwatch), for: .touchUpInside)
return cell
}
func selectedSwatch(sender: UIButton) {
//These set the "selected" border to the button you clicked on.
sender.layer.borderWidth = 2
sender.layer.borderColor = UIColor(red: 83/255, green: 71/255, blue: 65/255, alpha: 1.00).cgColor
}
}
で誰がどのように私の「selectedSwatch」機能で他のボタンへのアクセスを教えていただけますか?
私は、これは正しい軌道に乗って、確かだと思います。このメソッドを使用してコレクションビューのセル数を取得できます。どのように返された配列を使用して、セルの内部のUIButtonまでドリルダウンするのですか? のような何か: VAR allCells = trimSelector.visibleCells() allCells [0] <<ここに何>> layer.borderColor = UIColor.black –
あなたのコレクションビュー細胞UICollectionViewCellのカスタムサブクラスを作成します。?。。プロトタイプセルを定義し、ストーリーボードにコンセントを接続します。次に、呼び出しvisibleCellsから取得したセルをカスタムセルタイプにキャストし、コンセントを使用してボタンを探します。 –
セルプロトタイプの設定については、次のリンクを参照してください。http://www.techotopia.com/index.php/An_iPhone_iOS_6_Storyboard-based_Collection_View_Tutorial –