我有一个带有按钮的原型(prototype)标题 View ,我希望能够单击该按钮以转到另一个 View Controller (TargetViewController
)。
但是,由于某种原因,我无法让它工作。我正在尝试以编程方式完成这一切,因此没有像我通常习惯的 prepareForSegue
函数。你能告诉我我做错了什么吗?
如果使用委托(delegate),我还需要 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")
}
}
TableView Controller :
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
}
}
目标 View Controller :
import UIKit
extension TargetViewController: HeaderCellDelegate {
func didTapEdit() {
print("editButtonPressed")
}
}
最佳答案
如果没有委托(delegate),您可以在 ProfileDataController
中添加操作
extension ProfileDataController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderCell") as! HeaderCell
header.editButton.addTarget(self, action: #selector(editButtonPressed), for: .touchUpInside)
return header
}
}
在 ProfileDataController
中
@objc func editButtonPressed() {
print("edit button pressed")
self.performSegue(withIdentifier: "YOUR SEGUE IDENTIFIRE", sender: nil)
}
关于ios - HeaderView 按钮以编程方式转到另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821225/