ios - 带有按钮的 Swift UitableViewcell

标签 ios swift uitableview

我在 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) 和许多其他按钮。

enter image description here

最佳答案

这是因为 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/

相关文章:

ios - 使用 PresentViewController 而不是 Storyboard 不会显示单元格数据?

ios - 为什么我在导航 Controller 以编程方式返回后看不到顶部栏

ios - 在 Swift 中使用泛型协议(protocol)实现委托(delegate)

ios - UITableView 中的 NSUserDefaults 和持久性

ios - 如何上传到 S3 存储桶使用 iOS 相机拍照

ios - 如何(我可以)从 NSFetchedResultsController 获取其他部分的内容吗?

ios - 无法使用 JSON 数据设置 UITableView 部分标题

ios - 与 assetsd 的连接中断或 assetsd 死亡(带有内存警告)

ios - 按 channel 名称检索 YouTube channel 视频

ios - iOS 中徒手画图 - 需要使用积分