Adding a Right “done” Button (UIBarButtonItem) to

2019-03-28 11:45发布

问题:

I see that a similar question was asked here: How to add a right button to a UINavigationController? (among others) but its not quite what I'm looking to do and they arent solving my problem.

Essentially, I've created a UIViewController called WebViewViewController with a UIWebView on it which will be shown using presentModalViewController. Essentially its a mini web browser to display a web page while keeping the user in the app rather than launching Safari.

The viewController does the following to get it to show... and the "done" button is meant to provide a place to close the browser.

-(IBAction)visitFacebook {
    WebViewViewController *rootController = [[WebViewViewController alloc] init];
    rootController.webURL = @"http://www.facebook.com/";
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc ] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(done:)];

    [navigationController.navigationItem setRightBarButtonItem:doneButton animated:YES];
    [navigationController.navigationItem setTitle:@"Facebook"];

    if (rootController) {
        [self presentModalViewController:navigationController animated:YES];
    }

    [doneButton release];
    [rootController release];
}

Unfortunately the "done" button isnt showing.. any ideas where im going wrong?

回答1:

Try with below

-(IBAction)visitFacebook{
WebViewViewController *rootController = [[WebViewViewController alloc] init];
rootController.webURL = @"http://www.facebook.com/";
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc ] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(done:)];

 rootController.navigationItem.rightBarButtonItem = anotherButton;

[navigationController.navigationItem setTitle:@"Facebook"];

if (rootController) {
    [self presentModalViewController:navigationController animated:YES];
}

[doneButton release];
[rootController release];

}


回答2:

Perhaps you're looking for something more like this:

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                      style:UIBarButtonItemStyleDone target:self 
                                     action:@selector(dismissModalViewControllerAnimated:)];


回答3:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done"
        style:UIBarButtonItemStylePlain target:self action:@selector(done:)];

Just this one line code displayed done button for me.