嗨,我正在开发食物应用程序,该应用程序在 collectionviewcell 中有食物,我在单元格中添加了复选框,所以我如何通过复选框从单元格中选择一些食物, 我在 Collection View 单元格中添加复选框并为按钮添加类,但是当我单击第一个单元格中的复选框时,所有其他单元格都被选中,
复选框代码
var isCheckedGlobal = Bool() // !! Global Variable // You might need to change '= Bool()' to '= false' or '= true'
class CheckBox: UIButton {
//images
let checkedImage = UIImage(named: "checked") as UIImage?
let unCheckedImage = UIImage(named: "unchecked")as UIImage?
//bool propety
var isChecked:Bool = false{
didSet{
if isChecked == true{
self.setImage(checkedImage, forState: .Normal)
}else{
self.setImage(unCheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender:UIButton) {
if(sender == self){
if isChecked == true{
isChecked = false
isCheckedGlobal = false // !! Set variable's value
}else{
isChecked = true
isCheckedGlobal = true // !! Set variable's value
}
}
}
}
在collectionview中这段代码
if let foodcodes = self.menu![indexPath.row]["code"] as? NSString {
if isCheckedGlobal == false {
cell.foodNumber.enabled = false
cell.foodNumber.text = ""
} else {
if cell.foodNumber.tag == cell.checkboxx.tag {
cell.foodNumber.enabled = true
cell.foodNumber.text = "1"
}
}
}
最佳答案
1.首先制作一个全局可变数组,如arrSelectedCells
2.现在在 UICollectionView cellForRow
中设置 indexpath.row
值作为复选框按钮的标签。
3.在 buttonClicked
Action 中,从按钮中获取标签值并将标签值存储在 arrSelectedCells
中,同时检查标签是否存在于 arrSelectedCells
如果存在则将其删除。这样 arrSelectedCells
中就不会存在多个相同的值标记。
4.现在,UICollectionView cellForRow
,检查 indexpath.row
值是否存在于 arrSelectedCells
中,如果存在则启用复选框,否则禁用复选框。
关于ios - uicollectionviewcell swift ios 中的自定义复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30572732/