Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1578
一个人的身影
一个人的身影 2020-11-27 10:31

How can I change the position of a UIBarButtonItem in a UINavigationBar? I would like my button to be about 5px higher than its normal position.

20条回答
  •  孤街浪徒
    2020-11-27 11:19

    The best way is to subclass your UINavigationBar, as described here: https://stackoverflow.com/a/17434530/1351190

    Here is my example:

    #define NAVIGATION_BTN_MARGIN 5
    
    @implementation NewNavigationBar
    
    - (void)layoutSubviews {
    
        [super layoutSubviews];
    
        UINavigationItem *navigationItem = [self topItem];
    
        UIView *subview = [[navigationItem rightBarButtonItem] customView];
    
        if (subview) {
    
            CGRect subviewFrame = subview.frame;
            subviewFrame.origin.x = self.frame.size.width - subview.frame.size.width - NAVIGATION_BTN_MARGIN;
            subviewFrame.origin.y = (self.frame.size.height - subview.frame.size.height) / 2;
    
            [subview setFrame:subviewFrame];
        }
    
        subview = [[navigationItem leftBarButtonItem] customView];
    
        if (subview) {
    
            CGRect subviewFrame = subview.frame;
            subviewFrame.origin.x = NAVIGATION_BTN_MARGIN;
            subviewFrame.origin.y = (self.frame.size.height - subview.frame.size.height) / 2;
    
            [subview setFrame:subviewFrame];
        }
    }
    
    @end
    

    Hope it helps.

提交回复
热议问题