ios - 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?

标签 ios swift uitableview

我有一个 FlagButton,它扩展了 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
    // ...
}

最佳答案

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

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

关于ios - 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55468074/

相关文章:

ios - 为什么 UIView 的 intrinsicContentSize 总是返回 (-1.0, -1.0)?

iphone - 添加按钮以推送通知警报

ios - Swift:以编程方式导航到 ViewController 并传递数据

swift - 在 swift 中实现手势识别器后,如何找到按钮标签?

ios - Xcode 存档按钮已禁用

ios - 如何从 Firebase 快照设置变量 (swift)

ios - 如何重用 UITableView 中的单元格

ios - 当我像在 ios 中的 Flipkart 中一样将表格 View 滚动到底部时,如何在表格 View 中显示事件指示器?

iphone - 使用 CALayer 将对角线横幅/角标(Badge)添加到 UITableViewCell 的角

swift - 在 Tableview 中设置静态位置 View (Swift)