我通常是Swift的新手。我有两个图像,我希望它们像复选框一样,第一个图像是未选中框,第二个图像是复选框,通过使用didSelectItemAt indexPath:在集合视图中,当用户点击该集合视图时,我将如何在两个图像之间切换。我有点困惑。继承我的代码:
var buttonCounter = 0
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return faultyType.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "faulty_type_cell", for: indexPath) as! FaultyTypeCollectionViewCell
cell.faultyTypeLabel.text = faultyType[indexPath.row]
if buttonCounter == 0{
cell.checkboxImage.image = UIImage(named: "Checkboxunpicked")
}
else if buttonCounter == 1{
cell.checkboxImage.image = UIImage(named: "Checkboxpicked")
}
else if buttonCounter == 2{
cell.checkboxImage.image = UIImage(named: "Checkboxpicked")
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row == 1{
buttonCounter = 1
}
if indexPath.row == 2{
buttonCounter = 2
}
}
答案 0 :(得分:0)
我在网上搜索后找到了一个很好的解决方案。下面是我提到的解决方案:[link] How to access buttons in a UICollectionView from a target function set (Swift 3)快乐的编码狩猎。
var BoxOn = UIImage(named: "Checkboxpicked")
var BoxOff = UIImage(named: "Checkboxunpicked")
var buttonCounter = [Int]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "faulty_type_cell", for: indexPath) as! FaultyTypeCollectionViewCell
cell.faultyTypeLabel.text = faultyType[indexPath.row]
cell.checkboxImage.image = BoxOff
if buttonCounter.contains(indexPath.row){
cell.checkboxImage.image = BoxOn
}
else{
cell.checkboxImage.image = BoxOff
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if buttonCounter.contains(indexPath.row){
let index = buttonCounter.index(of: indexPath.row)
buttonCounter.remove(at: index!)
collectionView.reloadItems(at: [indexPath])
}
else{
buttonCounter.append(indexPath.row)
collectionView.reloadItems(at: [indexPath])
}
print(buttonCounter)
}