我已经在表格视图中添加了数据,并且我已经手动添加“全选”选项以便在第一个位置列出现在当用户选择第一个选项时选择全部,然后选择列表中的所有项目并在选择相同时取消选择.我已经尝试过下面的代码,但它没有工作,所以任何人都可以帮我解决这个问题
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
for i in 0 ..< self.getStudentName.count {
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
print (i) //i will increment up one with each iteration of the for loop
}
}
var unchecked = true
@IBAction func btnCheckBoxClick(_ sender: Any) {
if unchecked == true {
//(sender as AnyObject).setImage(UIImage(named: "selectedItem"), for: .normal)
cell?.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
//unchecked = false
let cello = ObjTableview.cellForRow(at: indexPath!)
print(cello!)
ObjTableview.reloadData()
}else
{
//(sender as AnyObject).setImage(UIImage(named: "unSelectedItem"), for: .normal)
cell?.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
// unchecked = true
}
}
最佳答案 Jayprakash,你快到了.你需要修改一些行 –
这是您修改后的代码段
var unchecked:Bool = true
@IBAction func btnCheckBoxClick(_ sender: Any) {
if(unchecked){
unchecked = false
}
else{
unchecked = true
}
ObjTableview.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(indexPath.row == 0){
btnCheckBoxClick(sender: UIButton())
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell : SelectUserCell!
cell = tableView .dequeueReusableCell(withIdentifier: "SelectUserCell", for: indexPath) as! SelectUserCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
if(unchecked){
cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
}
else{
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
}
// Do your stuff here
return cell
}
跳它将简化您的代码结构.