我有一个带有自定义弹出窗口的应用程序,其中包含一个表格视图(请参见下文)。当我点击一个复选框(UIButton)时,我换出背景图像并在选中和未选中之间切换。当我有一个复选框时,当我向上或向下滚动时,该复选框默认恢复为未选中状态。请问有人在滚动时如何保持每个单元格的检查状态吗?
class CustomHashTagPopup: UIViewController, UITableViewDelegate, UITableViewDataSource{
// CREATE TABLEVIEW CELLS
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableViewPicker.dequeueReusableCell(withIdentifier: "pickerCell") as! PreviewTableViewCustomPickerCell
if(indexPath == [0,0]){
let image = UIImage.init(named: "add")
cell.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
cell.pickerLabel.text = "Create New HashTag"
cell.isCreateTagCell = true
}else{
let image = UIImage.init(named: "uncheck")
cell.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
cell.pickerLabel.text = arrayHashTags[indexPath.row]
cell.isCreateTagCell = false
}
return cell
}
}
class PreviewTableViewCustomPickerCell: UITableViewCell {
var isSelect: Bool = false
var isCreateTagCell: Bool = false // TO DISTINGUISH 'CEATE NEW HASHTAG OPTION'
/*** OUTLETS ***/
@IBOutlet weak var checkBoxOutlet: UIButton!
@IBOutlet weak var pickerLabel: UILabel!
// TAP ON CHECK BOX
@IBAction func checkBoxBtn(_ sender: Any) {
if(isSelect == false && isCreateTagCell == false){
isSelect = true
// SHOW GREEN SELECTED CHECK BOX
let image = UIImage.init(named: "tick")
self.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
}else if(isSelect == true && isCreateTagCell == false){
isSelect = false
// SHOW UNCHECKED BOX
let image = UIImage.init(named: "uncheck")
self.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
}
}
}
答案 0 :(得分:1)
您错过的事情是单元重用,您必须将每个动作存储在模型数组中并检查当前值,并在cellForRowAt
内设置适当的设置,您可以将动作的委托设置为vc用于cellForRowAt
中的按钮,以便在用户单击特定indexPath上的按钮时轻松访问模型数组以对其进行操作,因此请考虑像这样声明数组
let arr = [false,true,false,false,false] first index is dummy as it will be skipped in Create New HashTag
//
@objc func btnClicked(_ sender:UIButton) {
arr[sender.tag] = !arr[sender.tag]
// reload indexPath of row = sender.tag , section = 0
}
//
在cellForRowAt
内
if (indexPath == [0,0]) {
let image = UIImage(named: "add")
cell.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
cell.pickerLabel.text = "Create New HashTag"
cell.isCreateTagCell = true
}else{
let image = UIImage(named: arr[indexPath.row] ? "tick" : "uncheck") // edited here
cell.checkBoxOutlet.setBackgroundImage(image!, for: .normal)
cell.pickerLabel.text = arrayHashTags[indexPath.row]
cell.isCreateTagCell = false
}
cell.button.addTarget(self, action: #selector(btnClicked(_:)), for: .touchUpInside)
cell.button.tag = indexPath.row