iOS11 导航栏适配<一>

2017-10-30  本文已影响303人  wustzhy

看代码

UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                               initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                               target:nil action:nil];
            
            negativeSpacer.width = kNegativeSpacer;  // iOS11 负数失效!, 重写navigationBar解决

            viewController.navigationItem.leftBarButtonItems = @[negativeSpacer,leftButtonItem];

查原因
以上没毛病,但iOS 11貌似出了bug。负宽度的negativeSpacer无效!

找解决

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

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (@available(iOS 11, *)) {
        self.layoutMargins = UIEdgeInsetsZero;
        
        for (UIView *subview in self.subviews) {
            if ([NSStringFromClass([subview class]) containsString:@"ContentView"]) {
                UIEdgeInsets oEdges = subview.layoutMargins;
                subview.layoutMargins = UIEdgeInsetsMake(0, oEdges.left+kNegativeSpacer, 0, oEdges.right+kNegativeSpacer);
            }
        }
    }
}

-(void)layoutSubviews{
    [super layoutSubviews];

    if (@available(iOS 11, *)){
      [self updateNavigationBar];
    }
}

- (void) updateNavigationBar {

    for(UIView *view in self.subviews) {
        if ([NSStringFromClass([view class]) containsString:@"ContentView"]) {

            // Adjust left and right constraints of the content view
            for(NSLayoutConstraint *ctr in view.constraints) {
                if(ctr.firstAttribute == NSLayoutAttributeLeading || ctr.secondAttribute == NSLayoutAttributeLeading) {
                    ctr.constant = 2.5;
                } else if(ctr.firstAttribute == NSLayoutAttributeTrailing || ctr.secondAttribute == NSLayoutAttributeTrailing) {
                    ctr.constant = -5.f;
                }
            }

            // Adjust constraints between items in stack view
            for(UIView *subview in view.subviews) {
                if([subview isKindOfClass:[UIStackView class]]) {
                    for(NSLayoutConstraint *ctr in subview.constraints) {
                        if(ctr.firstAttribute == NSLayoutAttributeWidth || ctr.secondAttribute == NSLayoutAttributeWidth) {
                            ctr.constant = 0.f;
                        }
                    }
                }
            }
        }
    }
}
but, 方式2 , 人眼能看到UI的leftItem调整动画,不理想!

参考
https://forums.developer.apple.com/message/238664#238664
https://stackoverflow.com/questions/44677018/ios-11-uinavigationbar-bar-button-items-alignment/46660888#46660888
https://tech.meituan.com/iPhoneX刘海打理指北.html
http://www.jianshu.com/p/383cdad95a32

上一篇下一篇

猜你喜欢

热点阅读