我是 Swift 的新手。我被困在这里了。我希望当我点击按钮时,单元格会更改并显示警告,但我认为我在某个地方错了。请给我解释一下。当我提出问题时,我会考虑很多。
代码如下:
@objc func handleTap(_ sender: UITapGestureRecognizer) {
ManagerProfileTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "managerProfileCell") as! ManagerInformationTableCell
let cellButton = tableView.dequeueReusableCell(withIdentifier: "buttonUpdateProfile") as! UpdateProfileTableCell
if indexPath.row == titlesInformationArr.count - 1 {
cellButton.updateButton.setTitle("Update", for: UIControlState.normal)
cellButton.updateButton.layer.cornerRadius = 5
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_: )))
cellButton.updateButton.isUserInteractionEnabled = true
cellButton.updateButton.addGestureRecognizer(tap)
if cell.informationTextField != nil {
cell.warningImage.isHidden = true
} else {
cell.warningImage.isHidden = false
}
return cellButton
} else {
cell.informationTextField.text = titlesInformationArr[indexPath.row].value
cell.titlesLabel.text = titlesInformationArr[indexPath.row].title
return cell
}
最佳答案
您的 cellButton
可能不应该是一个可重用的单元格 - 这就是 cell
是什么 - 但您添加到出队的可重用单元格的 UIButton。如果你这样添加它,你必须考虑单元格的生命周期。因为它是可重复使用的,所以即使它以前被使用过并且已经有一个按钮,你也会冒着向单元格添加一个按钮的风险......除非你正在做相反的事情,并删除按钮,使用 prepareForReuse()
(当你上下滚动时,当一个单元格离开屏幕时,它会回到一个单元格池中以供重复使用,并且可以返回给你,在它消失时的状态,就像你调用 dequeueReusableCell
.)
在这种情况下,您最好在界面生成器中设计原型(prototype)单元格并在其中添加按钮,然后子类化 UITableViewCell 并在该子类中为按钮事件 touchUpInside
创建 IBAction。当接收到该操作时,单元格可以执行一些操作,可能包括调用委托(delegate)方法,其中持有 TableView 的 View Controller 是委托(delegate),以执行与 TableView 相关的操作,如 reloadData()
在你的例子中。
如果您只想检测单元格中任何地方的点击,单元格已经可以做到这一点 - 只需确保 UITableViewDelegate 已连接 - 通常连接到实现 UITableViewDataSource 的相同位置 - 并实现方法 func tableView(UITableView, didSelectRowAt: IndexPath)
.您应该能够在此站点上找到大量使用此方法的示例。
如果您想知道您看到的警告可能意味着什么,您可以编辑答案并将其包含在内吗?
关于ios - 当按钮收到事件时,UITapGestureRecognizer 到 cellForRowAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199614/