1

我有这个问题,希望你能帮助我。

这是我的代码viewForHeaderInSection

let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(action), for: .touchUpInside)
view.addSubview(button)

这是 action功能:

@objc func action(sender: UIButton) {
    let position: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
    if let indexPath = self.tableView.indexPathForRow(at: position) {
        let section = indexPath.section
        print(section)
    }
}

现在,如果我点击除第一个标题(标题 0)以外的每个标题,它会打印正确的部分。如何让它也检测到标头 0?

4

1 回答 1

2

如果您想知道哪个是按钮的部分,您可以将该部分分配给按钮的标签,例如:

在你的viewForHeaderInSection

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
   button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
   button.addTarget(self, action: #selector(action), for: .touchUpInside)
   view.addSubview(button)
   button.tag = section // this is the trick
}

然后在动作内部:

@objc func action(sender: UIButton) {
    let section = sender.tag
    print(section)
}
于 2017-11-14T12:00:42.037 回答