Adding a Right “done” Button (UIBarButtonItem) to

2019-03-28 11:14发布

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?

3条回答
Melony?
2楼-- · 2019-03-28 11:53

Perhaps you're looking for something more like this:

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                      style:UIBarButtonItemStyleDone target:self 
                                     action:@selector(dismissModalViewControllerAnimated:)];
查看更多
男人必须洒脱
3楼-- · 2019-03-28 11:59
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done"
        style:UIBarButtonItemStylePlain target:self action:@selector(done:)];

Just this one line code displayed done button for me.

查看更多
贪生不怕死
4楼-- · 2019-03-28 12:04

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];

}
查看更多
登录 后发表回答