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

标签 ios swift

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

    @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/

相关文章:

ios - 设置导航后退按钮和导航 View 堆栈?

ios - 注册按钮点击功能

ios - 从 Parse 查询 GeoPoint 并将其作为 MKAnnotation 添加到 MapKit?

ios - Swift 3.0 或 Swift 2.3 最低系统版本要求,是否部署在 iOS 7 中

ios - Swift中反引号的实际应用

ios - 在 swift 4 中修改 [UInt8] 字节数组的最佳方法是什么?

iphone - 我可以更改导航栏项目的位置吗?

ios - 如何在宏(define)中使用if else?

ios - 是否可以在 Apple Watch 中创建图表?

ios - 使用 Swift 的 IOS 上的 XMPP 连接问题