我有一个 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/