Add a navigation bar to a view without a navigation controller

前端 未结 4 1305
情书的邮戳
情书的邮戳 2020-12-09 15:49

I have a side menu that slides out to display a table view and from there I have segues that use the reveal view controller. The segue has to connect directly to the view co

4条回答
  •  [愿得一人]
    2020-12-09 16:27

    While there are several smart ways to answer your question. I just solved it programmatically and wrote the following code in my viewWillAppear (note - viewDidLoad is also okay, but not suggested) -

    -(void) viewWillAppear:(BOOL)animated {
    
        UINavigationBar *myNav = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        [UINavigationBar appearance].barTintColor = [UIColor lightGrayColor];
        [self.view addSubview:myNav];
    
    
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:nil];
    
        UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                     style:UIBarButtonItemStyleBordered
                                                                    target:self action:nil];
    
    
        UINavigationItem *navigItem = [[UINavigationItem alloc] initWithTitle:@"Navigation Title"];
        navigItem.rightBarButtonItem = doneItem;
        navigItem.leftBarButtonItem = cancelItem;
        myNav.items = [NSArray arrayWithObjects: navigItem,nil];
    
        [UIBarButtonItem appearance].tintColor = [UIColor blueColor];
    }
    

    So, you have a white navigation bar with blue bar button items without a Navigation controller. Again, there are other ways to implement it in your case. Hope, this was helpful.

    Output -

    enter image description here

    Update -

    To add images -

    UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,10,32,32)];
    [myImage setImage:[UIImage imageNamed:@"image.png"]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myImage];
    [self.view addSubview:myImage];
    

提交回复
热议问题