【发布时间】:2016-11-27 23:20:36
【问题描述】:
在我的视图控制器中,我有一个集合视图,它在渲染时显示 3 个单元格,每个单元格都有一个标签和一个按钮。标签显示颜色的名称,按钮具有显示色样的背景图像。
我希望这样,每当您单击其中一个按钮时,该按钮周围会出现深色边框,而其他按钮上会出现浅色边框,以指示单击的按钮被“选中”。或者,我可以通过根据图像的选定状态更改图像来做到这一点 - 但我的问题仍然是一样的。
如何访问其他两个按钮以切换它们的属性?
我实现了一个脚本,允许我为某人单击的按钮添加边框 - 但我无法弄清楚如何访问 CollectionView 的其他单元格中的其他按钮以更改其边框属性。
这是我的源代码(去掉了不相关/不相关的位)
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”功能中的其他按钮?
【问题讨论】:
标签: ios uicollectionview swift3 xcode8