UITableViewController为节添加标题

时间:2011-10-13 07:23:48

标签: ios uitableview uikit

我有UITableView个多个部分。每个部分都有一个部分标题(自定义视图)是否有一种简单的方法来检测有人选择部分标题? (就像didSelectRowAtIndexPath一样,但是对于标题?)

4 个答案:

答案 0 :(得分:67)

这与@rckoenes答案完全不同,但它确实提供了一种更正统的方式来处理视图上的事件,而不是使用隐形按钮。

我宁愿在我的标题视图中添加UITapGestureRecognizer,而不是添加隐藏按钮并调整它们的大小:

UITapGestureRecognizer *singleTapRecogniser = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease];
[singleTapRecogniser setDelegate:self];
singleTapRecogniser.numberOfTouchesRequired = 1;
singleTapRecogniser.numberOfTapsRequired = 1;   
[yourHeaderView addGestureRecognizer:singleTapRecogniser];

然后:

- (void) handleGesture:(UIGestureRecognizer *)gestureRecognizer;

您可以使用gesture.view查看触摸的内容。然后做你需要做的任何事情来找出它是哪个标题(标签,数据阵列查找...)

答案 1 :(得分:27)

没有办法使用UITableViewDelegate

您可以做的是添加一个与标题页面视图大小相同的按钮,并将其添加到视图中。将按钮的标记设置为节索引。 然后,只需添加UIViewController作为UIControlEventTouchUpInside的目标。

然后,通过查看按钮的标签,您可以看到单击了哪个部分。

答案 2 :(得分:4)

以下是Swift 2中对我有用的内容:

h2 /* from h1 to h2, for example */ {
  font-size: 1.5em;
  margin: 0;
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 1em;
}

答案 3 :(得分:0)

这适用于评估部分和行。我希望它可以帮助其他正在努力使这项工作正常运转的人......

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)")
                    }
                }
            }
        }
    }
}