如何从自定义TableViewCell访问ViewController的navigationController

时间:2016-10-21 05:06:06

标签: ios swift uitableview

我有一个UITableView,我想为它实现一个自定义标头。在自定义标题中,我想要一个按钮,当点按时将新视图推送到navigationController。我在自定义标题视图的超级ViewController中访问navigationController时遇到了问题。

class CustomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    //setup views and whatnot
    //setup delegate and datasource


    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return CustomHeaderView(type: section)
    }
}

class CustomHeaderView : UIView {
    let customHeaderButton : UIButton = {
        let button = UIButton()
        ...
        button.addTarget(self, action: #selector(handleCustomHeaderButtonAction()), for: .touchUpInside)
        return button
    }()
    ...
    func handleCustomHeaderButtonAction(){
        //push a new view onto the CustomViewController's navigationController
        ???
}

3 个答案:

答案 0 :(得分:2)

试试这个:

class SecondViewController: UIViewController,ChildDelegate {


    internal func navigatToCustomViewController() {
        // Code to write push yur controller
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        let customview = customView()
        customview.delegate = self

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// A Protocol
protocol ChildDelegate: class {
    func navigatToCustomViewController()
}

// You custom view
class customView : UIView {

    weak var delegate: ChildDelegate?

    func actionDetailClick() {
        delegate?.navigatToCustomViewController()
    }
}

答案 1 :(得分:0)

试试这个;

1-10 #########################
11-20 ##############################
21-30 ######################

答案 2 :(得分:0)

我喜欢在这种情况下使用闭包:

class CustomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    //setup views and whatnot
    //setup delegate and datasource
    private func pushController() {
         // push your controller here
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = CustomHeaderView(type: section)
        view.pushHandler = pushController
        return view
    }
}

class CustomHeaderView : UIView {

    var pushHandler: (Void -> Void)?
    let customHeaderButton : UIButton = {
        let button = UIButton()
        ...
        button.addTarget(self, action: #selector(handleCustomHeaderButtonAction()), for: .touchUpInside)
        return button
    }()
    ...
    func handleCustomHeaderButtonAction() {
        pushHandler?()
    }
}