【问题标题】:iOS tableview cell button selection strange behavioriOS tableview 单元格按钮选择奇怪的行为
【发布时间】:2019-01-12 08:23:49
【问题描述】:

在 tableview 中,每个单元格都有一个书签图像按钮。点击它时,它会处于选中状态并显示图像(红色书签图标)。我有委托方法将带有选定按钮的单元格中的信息添加到数组中:

protocol CustomPoetCellDelegate {
func cell(_ cell: CustomPoetCell, didTabFavIconFor button: UIButton)
}

class CustomPoetCell: UITableViewCell {

@IBOutlet weak var poetNameLabel: UILabel!
@IBOutlet weak var verseCountLabel: UILabel!
@IBOutlet weak var periodLabel: UILabel!
@IBOutlet weak var iconButton: UIButton!

var delegate: CustomPoetCellDelegate?

override func awakeFromNib() {
    super.awakeFromNib()

    iconButton.setImage(UIImage(named: "icons8-bookmark-50-red.png"), for: .selected)
    iconButton.setImage(UIImage(named: "icons8-bookmark-50.png"), for: .normal)

    iconButton.isSelected = false
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

@IBAction func favIconTapped(_ sender: UIButton) {
    delegate?.cell(self, didTabFavIconFor: sender)
}

}

在tableViewController中:

func cell(_ cell: CustomPoetCell, didTabFavIconFor button: UIButton) {
    if !button.isSelected {
        let indexPathRow = tableView.indexPath(for: cell)!.row

        if isFiltering() {
            favoritePoets.append(searchResults[indexPathRow])
            button.isSelected = true
        } else {
            favoritePoets.append(poets[indexPathRow])
            button.isSelected = true
        }
    } else {
        button.isSelected = false

        favoritePoets = favoritePoets.filter { $0.arabicName !=  cell.poetNameLabel.text}
    }
}

isFiltering() 方法检查 searchBar 是否正在处理中。

现在,如果 isFiltering() 为假,一切都很好,但如果 isFiltering() 为真(即在 tableView 中搜索名称),当我点击特定单元格按钮以选择它然后单击取消时要关闭 searchBar,还选择了其他单元格的图标,尽管只有我点击的那个被添加到数组中。在视图中来回导航时,错误的选择消失了,只选择了正确的选择。

知道发生了什么吗?

提前致谢。

【问题讨论】:

    标签: ios swift uitableview uibutton uisearchbar


    【解决方案1】:

    问题在于 UITableView 重复使用单元格来优化滚动性能。因此,它重新使用不再在视图中的单元格和即将显示的新单元格。因此,您需要在更新/重用单元格时设置单元格的状态。

    每次都会调用以下函数。因此,您需要在此处设置选中或未选中状态的单元格属性。

         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            ...
            cell.indexPath = indexPath  //Create an indexPath property in your cell and set it here
                                       //This will be required when you call the delegate method
    
            //configure your cell state
    
            return cell
       }
    

    您可以通过更改您已经调用的委托方法中的特定属性来更新您的喜爱诗人数组中的模型,例如

      favoritePoets[indexPath.row].selected = true or false
    

    要访问 indexPath,您需要按照上面代码中的说明进行设置。然后在您的委托方法中将其作为参数传递。现在这个更新的属性将帮助你在 cellForRowAt 函数中设置你的状态。

    希望它有所帮助:)。欢迎发表评论。

    【讨论】:

    • 你是对的。这是由于重复使用细胞。我的工作方式基本上与您提到的相同。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2014-09-20
    • 2013-09-24
    • 2019-12-31
    • 2014-08-17
    相关资源
    最近更新 更多