【发布时间】:2018-02-16 06:28:50
【问题描述】:
我有一个带有按钮的原型标题视图,我希望能够单击该按钮以转到另一个视图控制器 (TargetViewController)。
但是,由于某种原因,我无法让它工作。我正在尝试以编程方式完成这一切,因此没有像我通常习惯的那样prepareForSegue 函数。你能告诉我我做错了什么吗?
如果使用委托,我还需要addTarget 吗?而且我认为最大的问题是我不知道应该将delegate 设置为哪个类。
我在这方面还很陌生,所以非常感谢任何帮助!
相关代码如下:
protocol HeaderCellDelegate: class {
func didTapEdit()
}
class HeaderCell: UITableViewHeaderFooterView {
var editButton: UIButton!
weak var delegate: HeaderCellDelegate?
override init(reuseIdentifier: String?) {
self.editButton = UIButton()
self.editButton.setImage(UIImage(named: "Edit"), for: .normal)
super.init(reuseIdentifier: reuseIdentifier)
self.editButton.addTarget(self, action: #selector(editButtonPressed), for: .touchUpInside)
self.contentView.addSubview(editButton)
// Plaeholder for constraints
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
@objc func editButtonPressed() {
delegate?.didTapEdit()
print("delegate didTapEdit")
}
}
表格视图控制器:
extension ProfileDataController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return tableViewSections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewSections[section].rows.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderCell") as! HeaderCell
return header
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! UITableViewCell
return cell
}
}
目标视图控制器:
import UIKit
extension TargetViewController: HeaderCellDelegate {
func didTapEdit() {
print("editButtonPressed")
}
}
【问题讨论】:
-
您想在按下编辑按钮时推送 viewController?
-
在 viewForHeaderInSection 委托函数中设置 'header.delegate = self'
-
@user3628240 查看我的答案
标签: ios swift uitableview swift4 swift-protocols