ios - 如何知道在 UITableView 的标题部分进行了哪些点击?

标签 ios uitableview swift

有时我有一个标题部分(只有一个,因为我只有一个部分)。我添加了如下手势(单击):

let singleTap = UIShortTapGestureRecognizer(target: self, action: "singleTap:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
tableView.headerViewForSection(0)?.addGestureRecognizer(singleTap)

它有效。问题是,当我的 tableView 只有几行时,如果我点击最后一行下方(空白区域),它也会触发手势。

如何避免?我在想一种方法可能是检查水龙头的位置是否在标题的范围内,但我不知道该怎么做。

对于普通行来说很简单,我只使用 tableView.indexPathForRowAtPoint(point: CGPoint) 但对于标题呢?

编辑:

当我调用 tableView.headerViewForSection(0) 时,我似乎需要注册我的标题才能得到一些东西,但问题是我的标题是一个 UIView,而不是一个UITableViewHeaderFooterViewUITableViewCell 所以我无法注册它(我想...)。

到目前为止它一直有效,因为我也在表格 View 上添加了手势。

因此,当手势被添加到整个 tableView 上时,当我从手势中获取 View 时,我得到的是 tableView 而不是标题。

所以我所做的是使用它的标签从 tableView 中获取 header :

let header = tableView.viewWithTag(Tag.Header.rawValue)

然后检查水龙头的位置,如果它在标题 View 内:

let location = sender.locationInView(sender.view)
if header!.pointInside(location, withEvent: nil) { ... }

最佳答案

可能更好的方法是在 viewController(tableView)的 mainView 上设置 gestureRecognizer,并在 gestureRecognizer 的手势 Action 中检测点击的 View :

{
    let singleTap = UIShortTapGestureRecognizer(target: self, action: "singleTap:")
    singleTap.numberOfTapsRequired = 1
    singleTap.numberOfTouchesRequired = 1
    tableView.addGestureRecognizer(singleTap)  // <--
}
...

@IBAction func singleTap(tapGestureRecognizer: UIShortTapGestureRecognizer) {
    // detect the tapped view
    var loc = tapGestureRecognizer.locationInView(self.tableView)

    if (CGRectContainsPoint(tableView.headerViewForSection(0)?.frame, loc)) {
        // header was tapped
        ...
    }
}

关于ios - 如何知道在 UITableView 的标题部分进行了哪些点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29648973/

相关文章:

ios - 在 prepareForSegue 中意外发现 nil IBOutlet

ios - 当 iOS 上的状态栏高度发生变化时,基于约束的布局不会动画化

ios - 循环遍历嵌套的 NSMutableDictionary 并过滤一些项目

ios - 在 UITableView 中拖动时添加一个单元格

javascript - 自定义 ios 键盘以显示数字键盘

ios - 如何使用标签栏自定义设计 ScrollView ?

ios - 加载股票 tableView 时出现 fatal error (发现为零)

ios - WatchKit - 如何移动标签或图像

ios - WatchKit 应用程序在进入后台后丢失数据 - Swift

swift - 使用核心数据查找重复条目