how to create back button in navigation bar

2019-01-15 06:20发布

问题:

I have 2 page. first is tableView and second is view when I to click on any cell go on to next page (view) in way modal segue. I want add back button in next page of navigation bar . this is my code in view page : ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.lable.text = obji.Name;
    self.lable2.text = obji.Descript;

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(Back)];
    self.navigationItem.leftBarButtonItem = backButton;
}

- (IBAction)Back
{
    //I dont know that how return pervious page
}

回答1:

As you said in your comment you use a modal controller

Add the following in viewWillappear

     UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:self action:@selector(Back)];
     self.navigationItem.leftBarButtonItem = backButton;

And in

- (IBAction)Back
  {
    [self dismissViewControllerAnimated:YES completion:nil]; // ios 6
  }


回答2:

Swift 3

let backButton: UIBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(back))
    self.navigationItem.leftBarButtonItem = backButton

func back() {
    self.dismiss(animated: true, completion: nil) }


回答3:

I had similar issue, but I am using Swift. Here is the answer in Swift 2.2.

        override func viewWillAppear(animated: Bool) {
            let backButton: UIBarButtonItem = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: #selector(back))
            self.navigationItem.leftBarButtonItem = backButton;
            super.viewWillAppear(animated);
        }

        func back() {
            self.dismissViewControllerAnimated(true, completion: nil)
        }