gpt4 book ai didi

ios - 这是为什么?按钮切换其背景图像被其他单元格重复使用的自定义单元格的状态

转载 作者:行者123 更新时间:2023-11-28 07:29:18 25 4
gpt4 key购买 nike

自定义单元格上切换背景图片状态的按钮,被其他单元格重用,应该是重用问题,但不知道如何解决?你能给我一些建议吗?

    @objc func LickCheck(_ sender:UIButton){
//Toggle button background image
if !sender.isSelected {
//code
}else{
//code
}
sender.isSelected = !sender.isSelected

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell : FoneCell = tableView.dequeueReusableCell(withIdentifier: "Focid", for: indexPath) as! FoneCell;

cell.xxBtn.tag = indexPath.row;

cell.xxBtn.addTarget(self, action: #selector(LickCheck), for: UIControl.Event.touchUpInside);

return cell;
}

FoneCell.swift:

lazy var xxxBtn : UIButton = {
let btn = UIButton();
btn.setImage(UIImage.init(named: "love_18x18_"), for: UIControl.State.normal);
btn.setImage(UIImage.init(named: "love_on_20x20_"), for: UIControl.State.selected)


return btn;
}();

最佳答案

在 UITableViewCell 的重写方法中

override func prepareForReuse() {
super.prepareForReuse()
//set default state here
self.imageView.image = nil
self.toggleButton.isOn = false
//.....
}

或者你可以在 tableViewcellForRowAtIndexPath 中做同样的事情

 let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

//Set default behaviour here
cell.imageView.image = nil
cell.toggleButton.isOn = false
....
return cell

P.S 你可以在 viewController 中创建数组来保存选中按钮的状态。例如

let isSelectedArray = Array(repeating: false, count: 100)
@objc func LickCheck(_ sender:UIButton){
//Toggle button background image
let tag = sender.tag
if !isSelectedArray[tag]{

//code
}else{
//code
}
isSelectedArray[tag] = !isSelectedArray[tag]
sender.isSelected = !sender.isSelected
}

关于ios - 这是为什么?按钮切换其背景图像被其他单元格重复使用的自定义单元格的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com