简体   繁体   中英

Set UIBarButtonItem target programmatically to previous view Controller

I have two UIViewController (I did not use UINavigationController) which are named as ParentViewController and ChildViewController.

However, I can't add UINavigationBar using storyboard for the child view controller, so I add the UINavigationBar with UIBarButtonItem inside it programmatically.

I've successfully add the navigation bar and the bar button item to the child view controller. The problem I got that I can't set the target for the UIBarButtonItem, so when it pressed, the Parent view controller will show up.

This is the code I use, but I didn't sure where to put them

let navigationBar : UINavigationBar = { //Label to display the text
    let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    navBar.translatesAutoresizingMaskIntoConstraints = false

    let navItem = UINavigationItem(title: "SomeTitle");
    let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: nil, action: "selector");
    let backItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(backAction(_:)));
    //let backItem: UIBarButtonItem = backsItem

    navItem.rightBarButtonItem = doneItem;
    navItem.leftBarButtonItem = backItem;
    navBar.setItems([navItem], animated: false);

    return navBar;
}();

@IBAction func backAction(_ sender: Any?) {
    self.navigationController?.popViewController(animated: true)
}

And then I add the navigationBar to the subView in Child View Controller viewDidLoad()

For your information, I did not do anything in the parent view controller. It just the segue I created on storyboard to show the child view controller when pressed.

please kindly help me...

I already found the solution. Instead of using self.navigationController to show the previous controller, I used the general present command to show the view controller.

This is my code, and it solved all of my problems.

let vc = self.storyboard?.instantiateViewController(withIdentifier: "ParentViewController")
self.present(vc!, animated:true, completion:nil)

I hope it will help the others who facing a problems like me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM