OGeek|极客世界-中国程序员成长平台

标题: ios - 当按钮接收到事件时,UITapGestureRecognizer 到 cellForRowAt [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:35
标题: ios - 当按钮接收到事件时,UITapGestureRecognizer 到 cellForRowAt

我是 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
    }



Best Answer-推荐答案


您的 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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4