完美解决iOS11 navigationItem不能偏移问题

iOS11以下偏移方案:

UIButton *settingBtn = [UIButton alloc]init]; 

UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithCustomView:settingBtn]; 

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; 

negativeSpacer.width = -10; 

self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,rightBar,nil];

iOS11发现以上方法不能用了,iOS11请看分割线下面


感谢 stackoverflow上的朋友提供的解决办法

https://stackoverflow.com/questions/44677018/ios-11-uinavigationbar-bar-button-items-alignment/46660888#46660888

首先自定义navigationBar,

#import "LZJNavigationBar.h"

@implementationLZJNavigationBar

static CGFloat const mySpacer = -5;//item边距设置

- (void)layoutSubviews {

    [super layoutSubviews];

    if(@available(iOS11, *)) {

        self.layoutMargins = UIEdgeInsetsZero;

    for(UIView*subviewinself.subviews) {

            if ([NSStringFromClass([subview class]) containsString:@"ContentView"]) {

                UIEdgeInsets myEdge = subview.layoutMargins;

                subview.layoutMargins=UIEdgeInsetsMake(0, myEdge.left+mySpacer,0, myEdge.right+mySpacer);

            }

        }

    }

}

@end

使用方法

 CustomViewController *VC =[[CustomViewController alloc]init];

    UINavigationViewController *nav = [[UINavigationViewController alloc] initWithNavigationBarClass:[LZJNavigationBar class] toolbarClass:nil];

    [nav setViewControllers:@[VC] animated:NO];

然后再使用最iOS11以下的偏移方法,生效!

完美解决

你可能感兴趣的:(完美解决iOS11 navigationItem不能偏移问题)