使用UITapGestureRecognizer

时间:2017-03-17 20:44:41

标签: ios swift uitableview uilabel uitapgesturerecognizer

我有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.locationUILabel个对象。我在这里要做的是检测UILabel上的点击事件。我查看了整个互联网,每个人都在建议这种方法,但是,这个代码在我的情况下不起作用。根本没有调用方法locationClicked。谁能告诉我我的代码有什么问题?

修改 还有一件事,以记忆方式这样做是一个好主意吗?我的意思是如果我们有一个长列表,那么将为每个单元格生成许多UIGestureRecognizer个对象。这是因为滚动项目时会调用该方法。

2 个答案:

答案 0 :(得分:0)

由于您要将单元格出列,因此您需要以某种方式获取对UITapGestureRecognizer的引用,并将其删除或重复使用。否则,每次重复使用单元格时,您将在已经在单元格上的单元格上放置另一个识别器。如果您是UITableViewCell的子类,则可以将识别器添加为属性。

但是,使用您发布的代码我建议您使用UIButton并添加标记,以便稍后获得对它的引用。您可以将按钮的边界设置为等于标签的边界。尝试这样的事情:

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"

    // If we don't already have a button on our cell, create one and set the tag
    if cell.viewWithTag(103) as? UIButton == nil {
        let newButton = UIButton(frame: cell.location.bounds)
        newButton.tag = 103
        newButton.addTarget(target: self, action: #selector(locationClicked), for: .touchUpInside)
    }
}

答案 1 :(得分:0)

似乎无法检测非UIControl视图上的点按,因此在这种情况下,我继续将UILabel更改为UIButton视图并对其进行样式设置所以它看起来像UILabel