简体   繁体   中英

How to add button to navigation bar

adding a button to navigation bar on first nib viewController and wanted to view this button to only on main screen not on any other screen i have worked out on it i made the button and added to subview of navigation bar on every button action i have put this

- (IBAction)forth:(id)sender {
    forthView *forthview = [[forthView alloc]init];
    [self.navigationController pushViewController:forthview animated:YES];
    btn.hidden = YES;
}

after this button hides but didnot show up when i got back to main screen my code for viewdidload is here

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title = @"My First View";

    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    btn = [[UIButton alloc] init];

    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(10, 10, 65, 30);
    [btn setTitle:@"Show" forState:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:btn];

    btn.hidden = false;

}

Once you hide the button so you need to unhide it again. here is the simple code to unhide the button:

btn.hidden = No

viewDidLoad is only called the first time your view is loaded. Add an NSLog() statement if you want to test when it gets called. Every time your view appers on screen viewWillAppear is called.
So you need to show the button in viewWillAppear

It seems likely that what you really want to be doing is adding a UIBarButtonItem to your main view controller's navigationItem.leftBarButtonItem property. That way the button will have the correct appearance and show and hide as the view controller is displayed.

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

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