我在 UITABLEVIEW 中有一个奇怪的行为。
我有一个带按钮的 TableView,我想做的是当我点击 tableView 中的一个按钮时,我希望颜色边框变为红色。
问题是颜色不仅会随着单击按钮的变化而变化,还会随着表格 View 中其他行的变化而变化:
这是我的实现
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! chooseProductTVC
cell.Btn_AddProduct.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
return cell
}
@objc func btnAction(_ sender: MyButton) {
sender.BorderColor = UIColor.red
let point = sender.convert(CGPoint.zero, to: tbl_View_ChooseProduct as UIView)
let indexPath: IndexPath! = self.tbl_View_ChooseProduct.indexPathForRow(at: point)
let object = self.fetchedResultsController.object(at: indexPath)
print (object.produit_name)
print("row is = \(indexPath.row) && section is = \(indexPath.section)")
}
正如您在下图中看到的,我只单击了第一个按钮 (Abricot) ==> 其他按钮也自动更改了边框 (Avocat) 和许多其他按钮。
最佳答案
这是因为 cell dequeuing 尝试在加载表时重新设置,假设这里默认为 blue
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell.Btn_AddProduct.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
if selected
cell.Btn_AddProduct.BorderColor = UIColor.red
else
cell.Btn_AddProduct.BorderColor = UIColor.blue
return cell
}
关于ios - 带有按钮的 Swift UitableViewcell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853326/