添加到单元格的点击手势是否保留在重复使用状态?

时间:2019-01-11 10:44:48

标签: ios swift uitableview

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

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) {
    }
}

1 个答案:

答案 0 :(得分:2)

简短答案:


长答案:

您不应该那样做。初始化单元格时添加轻击手势。这样,水龙头仅在创建时添加一次,而不是在每次重用时添加。

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)
    }
    .
    .
    .

}

如果使用情节提要,则应在awakeFromNib文件中执行与@DuncanC所指出的相同的操作。

override func awakeFromNib() {
    super.awakeFromNib()

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