Custom UINavigationBar's backButton?

前端 未结 3 1213
青春惊慌失措
青春惊慌失措 2021-01-02 20:58

I am making a iPhone app that allows the user to go back in a UINavigationBar. However, the way it looks now is horrendous. I am trying to customize it with my own image (mi

相关标签:
3条回答
  • 2021-01-02 21:33

    If you want to add UIButton to navigation bar via obj-c, your code should look like this:

    UIButton *button = /* initialize your button */
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [self.navigationItem setLeftBarButtonItem:barButtonItem];
    
    0 讨论(0)
  • 2021-01-02 21:37

    Combined the two answers and added the Back Button Functionality

    // Custom Navigation Bar Back Button
    
    // Create Button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(0,0,54,32); // width=54, height=32
    
    // Set Button Image
    NSString *backButtonURL = [[NSBundle mainBundle]pathForResource:@"back" ofType:@"png"];
    UIImage *backButtonImage = [UIImage imageWithContentsOfFile:backButtonURL];
    [button setBackgroundImage:backButtonImage forState:UIControlStateNormal];
    
    // Important: Set Button Action to go back
    [button addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    
    0 讨论(0)
  • 2021-01-02 21:44

    The problem is you are using UIButtonTypeRoundedRect instead UIButtonTypeCustom. You may also want to use:

    UIImage *image = [UIImage imageNamed:@"back_button_normal.png"]
    button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    
    0 讨论(0)
提交回复
热议问题