override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(sectionTapped(sender:)))
tableView?.addGestureRecognizer(tapGesture)
tapGesture.delegate = self as? UIGestureRecognizerDelegate
}
@objc func sectionTapped(sender: UITapGestureRecognizer) {
if sender.state == UIGestureRecognizerState.ended {
guard let tableView = self.tableView else {
return
}
if let view = sender.view {
let tapLocation = sender.location(in: tableView)
if let tapIndexPath = tableView.indexPathForRow(at: tapLocation) {
if (tableView?.cellForRow(at: tapIndexPath) as? UITableViewCell) != nil {
// do something with the row
print("tapped on row at index: \(tapIndexPath.row)")
}
} else {
for i in 0..<tableView.numberOfSections {
let sectionHeaderArea = tableView.rectForHeader(inSection: i)
if sectionHeaderArea.contains(tapLocation) {
// do something with the section
print("tapped on section at index: \(i)")
}
}
}
}
}
}
5条答案
按热度按时间svmlkihl1#
这与@rckoenes的答案没有根本的不同,但它确实提供了一种更正统的方式来处理视图上的事件,而不是使用不可见的按钮。
我宁愿在我的头视图中添加UITapGestureRecognizer,而不是添加不可见的按钮并调整它们的大小:
然后:
你可以使用gesture.view查看哪个被触摸了,然后做任何你需要做的事情来找出它是哪个头(标签,数据数组查找…)
0s0u357o2#
没有办法用
UITableViewDelegate
来做。你可以做的是添加一个按钮,大小与section header视图相同,并将其添加到视图中。将按钮的标签设置为section index。然后添加
UIViewController
作为UIControlEventTouchUpInside
的目标。然后通过查看按钮的标签,您可以看到单击了哪个部分。
rqmkfv5c3#
以下是我在Swift 2中的工作:
kcrjzv8t4#
这对评估部分和行起了作用。我希望它能帮助其他所有正在努力使这项工作正常进行的人...
gcmastyq5#
这里是Taku的回答的一个更新版本。