ios - 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?
问题描述
我有一个FlagButton
which 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
// ...
}
解决方案
其他单元格更改按钮的原因是 UITableView 正在重用单元格。因此,更改了按钮背景的单元格稍后会在函数中再次使用latestTableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostViewCell
您需要跟踪更改了哪个单元格。在您的dequeueReusableCell
函数中,检查它是否是同一个单元格,然后更改 UIButton 的背景,否则使其正常。
推荐阅读
- swiftui - 如何在 SwiftUI 中读取和过滤大型 Realm 数据集?
- asp.net-core - 在 PostAsJsonAsync 上接收空响应
- java - Java LWJGL OpenGL 3 将 3d 点转换为 2d 点
- powershell - Powershell 不返回哈希表中的键值
- mongoose - 如何根据其他 fieldName mongooseSchema 定义 slug
- reactjs - 如何将函数放入 React className 字段?
- c++ - 'distdir-am' 所需的目标'bootstrap' 没有规则。停止
- javascript - 如何从 HTML 表单中选择 HtmlService 和 ContentService 之间的 doGet(e) 函数?
- ios - 如何将可选链接与 nil 合并运算符一起使用?
- gtk - 是否可以在 gtk3 中隐藏弹出箭头?