首页 > 解决方案 > 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?

问题描述

我有一个FlagButtonwhich extends UIButton。我已将此添加到UITableCell. 点击按钮时,我想更改背景颜色,但仅适用于该单元格中的按钮。目前它也在改变其他单元格的颜色。

class FlagButton: UIButton {
    // ..

    func initStyle() {
        self.backgroundColor = UIColor.red
        self.setTitle("foo", for: .normal)
        self.setTitleColor(UIColor.black, for: .normal)
        self.addTarget(self, action: #selector(touchDown), for: .touchDown)
    }

    @objc func touchDown() {
        self.backgroundColor = UIColor.green
    }
}
class PostViewCell: UITableViewCell {
    var flagBtn: FlagButton?

    override func awakeFromNib() {
        super.awakeFromNib()
        flagBtn = FlagButton(frame: CGRect(x: 0, y: 0, width: 30, height: 20))
        guard let flagBtn = flagBtn else { return }
        flagBtn.initStyle()
        contentView.addSubview(flagBtn)
    }
}
// ..
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = latestTableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostViewCell
    // ...
}

标签: iosswiftuitableview

解决方案


其他单元格更改按钮的原因是 UITableView 正在重用单元格。因此,更改了按钮背景的单元格稍后会在函数中再次使用latestTableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostViewCell

您需要跟踪更改了哪个单元格。在您的dequeueReusableCell函数中,检查它是否是同一个单元格,然后更改 UIButton 的背景,否则使其正常。


推荐阅读