gpt4 book ai didi

ios - 使用 UITapGestureRecognizer 检测 UITableViewCell 内 UILabel 的点击事件

转载 作者:行者123 更新时间:2023-11-30 12:36:05 25 4
gpt4 key购买 nike

我有一个带有以下内容的 UITableViewDataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: OutletDetails.cellIdentifier) as! OutletDetails
cell.selectionStyle = .none
cell.isUserInteractionEnabled = true
cell.location = "Some location will be here"
let tap = UITapGestureRecognizer(target: self, action: #selector(locationClicked))
tap.cancelsTouchesInView = false
tap.numberOfTapsRequired = 1
cell.location.addGestureRecognizer(tap)
}

其中cell.location是一个UILabel对象。我在这里尝试做的是检测 UILabel 上的点击事件。我查遍了互联网,每个人都建议这种方法,但是,这个代码在我的情况下不起作用。 locationClicked 方法根本没有被调用。谁能告诉我我的代码有什么问题吗?

编辑还有一件事,从内存角度来说,这样做是个好主意吗?我的意思是,如果我们有一个很长的列表,那么将为每个单元格生成许多 UIGestureRecognizer 对象。这是因为滚动项目时会多次调用该方法。

最佳答案

向对象添加点击手势并启用其用户交互。是的,您也可以使用按钮。

//Adding tap gesture
let cellNameTapped = UITapGestureRecognizer(target: self, action: #selector(nameTapped))
nameLabel.isUserInteractionEnabled = true// UILabel made available for touch interaction
nameLabel.addGestureRecognizer(cellNameTapped) //gesture added

//Method called on touch of nameLabel
@objc func nameTapped(tapGestureRecognizer: UITapGestureRecognizer){
//print(tapGestureRecognizer.view)
}

关于ios - 使用 UITapGestureRecognizer 检测 UITableViewCell 内 UILabel 的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com