iOS 7: How to set UIBarButtonItem backButtonBackgroundImage for UIControlStateHighlighted?

前端 未结 3 1327
后悔当初
后悔当初 2021-02-19 13:02

I am trying to set the background image for back button in normal and highlighted states.

- (void)configureBackButtonInNavigationItem:(UINavigationItem *)item
{
          


        
3条回答
  •  粉色の甜心
    2021-02-19 13:30

    Currently Apple has bug on interactivePopGestureRecognizer (which makes to freeze navigation controller's view after swiping back on push animation, you will see nested pop animation can result in corrupted navigation bar warning in console), by the way, we can make a small hack to work around that bug.

    Here is a solution that works fine for me,

    Subclass a NavigationController class and make it to delegate the gesture

    @interface CBNavigationController : UINavigationController 
    @end
    
    @implementation CBNavigationController
    
    - (void)viewDidLoad
    {
      __weak CBNavigationController *weakSelf = self;
    
      if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
      {
        self.interactivePopGestureRecognizer.delegate = weakSelf;
        self.delegate = weakSelf;
      }
    }
    
    // Hijack the push method to disable the gesture
    
    - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
      if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.interactivePopGestureRecognizer.enabled = NO;
    
      [super pushViewController:viewController animated:animated];
    }
    
    #pragma mark UINavigationControllerDelegate
    
    - (void)navigationController:(UINavigationController *)navigationController
           didShowViewController:(UIViewController *)viewController
                        animated:(BOOL)animate
    {
      // Enable the gesture again once the new controller is shown
    
      if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.interactivePopGestureRecognizer.enabled = YES;
    }
    
    
    @end
    

    When the user starts swiping backwards in the middle of a transition, the pop events stack up and "corrupt" the navigation stack. My workaround is to temporarily disable the gesture recognizer during push transitions, and enable it again when the new view controller loads. Again, this is easier with a UINavigationController subclass.

    After this, you can calmly use item.leftBarButtonItem and UIButton as custom view.

提交回复
热议问题