有时我有一个标题部分(只有一个,因为我只有一个部分)。我添加了如下手势(单击):
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
,而不是一个UITableViewHeaderFooterView
或 UITableViewCell
所以我无法注册它(我想...)。
到目前为止它一直有效,因为我也在表格 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/