Setting a Custom Image for a Back Button on UINavigationBar

前端 未结 8 2159
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 10:55

I am trying to set a custom image for the back button that automatically gets place onto a navigation bar when a new view is pushed onto the stack.

I have tried add

相关标签:
8条回答
  • 2020-12-14 11:24

    iOS 8+ Swift version (can be converted to ObjC with not much effort). This method preserves all advantages and behaviour of navigation bar related to standard back button (animation on pushing/popping, interactive pop gesture, etc)

    // Call the code ONE TIME somewhere on app launch to setup custom back button appearance
    UINavigationBar.appearance().tintColor = UIColor.blackColor()
    // If you need custom positioning for your back button, in this example button will be 1 px up compared to default one
    // Also only vertical positioning works, for horizontal add offsets directly to the image
    let backImageInsets = UIEdgeInsetsMake(0, 0, -1, 0)
    // Get image, change of rendering (so it preserves offsets made in file), applying offsets
    let backImage = UIImage(named: "YourButtonImageAssetFileName")?.imageWithRenderingMode(.AlwaysOriginal).imageWithAlignmentRectInsets(backImageInsets)
    // Setting images
    UINavigationBar.appearance().backIndicatorImage = backImage
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
    
    // Call EACH TIME BEFORE pushing view controller if you don't need title near your back button arrow
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
    // Push controller
    self.navigationController?.pushViewController(vc, animated: true)
    
    0 讨论(0)
  • 2020-12-14 11:25

    try this code

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];  
    UIImage *backBtnImage = [UIImage imageNamed:@"BackBtn.png"]  ;  
    [backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];  
    [backBtn addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];  
    backBtn.frame = CGRectMake(0, 0, 54, 30);  
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn] ;  
    self.navigationItem.leftBarButtonItem = backButton;
    

    then define goback method like this

    - (void)goback
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    0 讨论(0)
提交回复
热议问题