ios - 添加到单元格的点击手势是否在重复使用时得到保留?

标签 ios swift uitableview

我有一个带有图像的单元格。我正在向它的 tableview 委托(delegate)方法添加点击手势。当单元格被重用时,点击手势是否重复?点击手势会发生什么?

class CalendarCell: UITableViewCell {
    @IBOutlet weak var locationImageView: UIImageView!
}

class CalendarViewController: UIViewController {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarCell
        let locationLabelTap = UITapGestureRecognizer(target: self, action: #selector(locationDidTap(recognizer:)))
        cell.locationLabel.addGestureRecognizer(locationLabelTap)
        return cell
    }

    @objc func locationDidTap(recognizer: UITapGestureRecognizer) {
    }
}

最佳答案

简短回答:


长答案:

你不应该那样做。在初始化单元格时添加点击手势。这样,tap 仅在创建时添加一次,而不是每次重复使用时添加。

class CalendarCell: UITableViewCell {

    //Your variable declaration and other stuff
    .
    .
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        //Adding subviews, constraints and other stuff
        .
        .
        .
        let locationLabelTap = UITapGestureRecognizer(target: self, action: #selector(locationDidTap(recognizer:)))
        locationLabel.addGestureRecognizer(locationLabelTap)
    }
    .
    .
    .

}

如果您正在使用 Storyboard,您应该在 awakeFromNib 文件中执行相同的操作,如 @DuncanC 所指出的那样.

override func awakeFromNib() {
    super.awakeFromNib()

    .
    .
    .
    let locationLabelTap = UITapGestureRecognizer(target: self, action: #selector(locationDidTap(recognizer:)))
    locationLabel.addGestureRecognizer(locationLabelTap)
}

关于ios - 添加到单元格的点击手势是否在重复使用时得到保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54144911/

相关文章:

ios - 如何创建渐变

ios - Xcode 9 : Swift dependency analysis error

swift - 转到详细的 TableView Controller

xcode - 将 UIImageView 的形状或大小更改为标准,以在 tableview 中圆形

ios - Unity3D child 应用程序中的家长门问题如何解决?

ios - 在 iphone 应用程序中实现 facebook 和 twitter 连接的最简单方法是什么?

ios - 为什么当我从我转至的 View Controller 返回时,我的 UITableView 的格式完全出错?

ios - 移动parentView时出现约束错误

swift - 在 Series 5 Watch 和 Watch OS6 上使用 `HKAnchoredObjectQuery` 返回心率值时出现问题

iphone - 如果第一次填充,如何限制 tableview 第二次填充单元格