我有一个带有图像的单元格。我正在向它的 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/