如何识别标签单击自定义UITableViewCell-Swift 3 [英] how to recognize label click on custom UITableViewCell - Swift 3
问题描述
我有一个自定义UITableViewCell
,在其上有一个Label
,需要根据特定条件使其可单击.因此,我在其上添加了TapGestureRecognizer
.我已经使用了相同的协议和委托.我想传递参数,并在单击此UILabel
时执行segue.我可以执行此segue,但无法检测到它是哪个单元的标签.
I have a custom UITableViewCell
on which I have a Label
, which needs to be made clickable depending on a certain condition. So I have added a TapGestureRecognizer
on it. I have used protocols and delegates for the same. I want to pass a parameter along with performing a segue on click of this UILabel
. I am able to perform this segue but cannot detect which cell's label was it.
我对此并不陌生,已经被困了几个小时.任何帮助,将不胜感激.还请告诉我是否有另一种更简单的方法来获得相同的结果.
I am new to this and have been stuck for a few hours. Any help would be appreciated. Please also tell me if there is another simpler way for the same result.
如果这是一个按钮,我可以添加一个目标,但是现在我真的很困.
If it would be a button I could have added a target but I am really stuck now.
推荐答案
正如@KrishnaCA在回答中所说,如果您希望整个标签都可单击,则最好使用按钮.如果您希望它看起来与按钮不同,还可以在标签顶部放置一个透明按钮(自定义样式,没有图像).
As @KrishnaCA says in their answer, if you want the whole label to be clickable it's probably better to use a button. If you need it to look different than a button, you can also place a transparent button (custom style with no image) on top of the label.
无论使用按钮还是标签+点击手势识别器,您仍然需要弄清楚用户点击了哪个indexPath.您可以按照Hamid的建议在按钮/标签中放置标签,但这很脆弱.我更喜欢另一种方式.我为UITableView编写了一个扩展,可让您找出哪个单元格拥有给定的视图:
Whether you use a button or a label + tap gesture recognizer you still need to figure out which indexPath the user tapped on. You can put a tag in the button/label as Hamid suggests, but that's fragile. I prefer a different way. I've written an extension to UITableView that lets you figure out which cell owns a given view:
public extension UITableView {
/// This method returns the indexPath of the cell that contains the specified view
/// - parameter view: The view to find.
/// - returns: The indexPath of the cell containing the view, or nil if it can't be found
func indexPathForView(_ view: UIView) -> IndexPath? {
let origin = view.bounds.origin
let viewOrigin = self.convert(origin, from: view)
let indexPath = self.indexPathForRow(at: viewOrigin)
return indexPath
}
}
如果将该扩展名添加到您的项目中,则可以使用以下代码.
If you add that extension to your project you can use code like below.
手势识别器:
@objc func alertClicked(sender: UIGestureRecognizer){
let view = sender.view
let indexPath = tableView.indexPathForView(view)
//Do whatever you need to do with the indexPath
}
或者,对于按钮操作:
@objc func buttonClicked(sender: UIButton) {
let indexPath = tableView.indexPathForView(sender)
//Do whatever you need to do with the indexPath
}
这篇关于如何识别标签单击自定义UITableViewCell-Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!