iOS11适配, 设置自定义导航栏按钮左/右间距为0

iOS11 刚发布, 现在正忙着适配, 由于导航栏的层级发生了改变, 所以之前使用UIBarButtonSystemItemFixedSpace的方式设置导航栏左/右按钮间距为0的方法在iOS11失效了, 小编在网上找了两天, 尝试了各种方法, 最后总结出适配的方法, 如有bug欢迎评论...

方案一

通过更改系统约束的方法来取消_UIButtonBarStackView的12和_UITAMICAdaptorView的8的间距

这是小编最初使用的方法
缺点: 改变系统私有API, 个人感觉不太稳妥

  • 自定义UINavigationController, 实现UINavigationControllerDelegate方法
#pragma mark - UINavigationControllerDelegate

//  每次viewController将要显示时都会调用此方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.viewControllers.count > 1) {
        /// 需要在0.01秒后调用, 否则可能获取不到UIStackView
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self resetNavigationBarItemSpaces];
        });
    }
}

- (void)resetNavigationBarItemSpaces {
    if ([[UIDevice currentDevice].systemVersion floatValue] < 11.0) { return; }
    for (UIView *barContentView in self.navigationBar.subviews) {
        if ([NSStringFromClass([barContentView class]) isEqualToString:@"_UINavigationBarContentView"]) {
            for (NSLayoutConstraint *constraint in barContentView.constraints) {
                if ([NSStringFromClass([constraint.secondItem class]) isEqualToString:@"_UINavigationBarContentView"] && constraint.firstAttribute == NSLayoutAttributeTrailing) {
                    // 移除UIStackView左/右边12的间距
                    if ( constraint.secondAttribute == NSLayoutAttributeTrailing) {
                        [barContentView removeConstraint:constraint];
                    } else if (constraint.secondAttribute == NSLayoutAttributeLeading) {
                        [barContentView removeConstraint:constraint];
                    }
                }
            }
            for (UIView *stackView in barContentView.subviews) {
                if ([stackView isKindOfClass:[UIStackView class]]) {
                    if (CGRectGetMinX(stackView.frame) < kScreen_Width * 0.5) {
                        [stackView.superview addConstraint:[NSLayoutConstraint constraintWithItem:stackView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:stackView.superview attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
                    } else {
                        [stackView.superview addConstraint:[NSLayoutConstraint constraintWithItem:stackView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:stackView.superview attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
                    }
                    // 移除UITAMICAdaptorView左/右边8的间距(bug:当同一边有多个item时,其之间也没有间距)
                    for (NSLayoutConstraint *constraint in stackView.constraints) {
                        if ([constraint.firstItem isKindOfClass:[UILayoutGuide class]]) {
                            if (constraint.firstAttribute == NSLayoutAttributeWidth && !constraint.secondItem) {
                                [stackView removeConstraint:constraint];
                                break;
                            }
                        }
                    }
                }
            }
            break;
        }
    }
}

方案二

改变button的内容偏移和响应区域, 此方案同样适用iOS11之前

1. 设置button的内容偏移

  1. 自定义UINavigationController, 实现UINavigationControllerDelegate方法;
  2. 在- (void)navigationController: willShowViewController: animated:方法中设置button的内容偏移; 你也可以在button创建的时候设置, 但需要在每个自定义UIBarButtonItem的控制器中都写一遍偏移的代码;
  • 优点: 可以改变所有控制器的navigationItem的间距, 便于维护
  • 缺点: 每次控制器将要显示时都要设置button的内容偏移; 但也只是调用一次, 对性能影响不大, 所以本人选择在此设置button的内容偏移
#pragma mark - UINavigationControllerDelegate

//  每次viewController将要显示时都会调用此方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [self resetBarItemSpacesWithController:viewController];
}
- (void)resetBarItemSpacesWithController:(UIViewController *)viewController {
    CGFloat space = kScreen_Width > 375 ? 20 : 16;
    for (UIBarButtonItem *buttonItem in viewController.navigationItem.leftBarButtonItems) {
        if (buttonItem.customView == nil) { continue; }
        /// 根据实际情况(自己项目UIBarButtonItem的层级)获取button
        UIButton *itemBtn = nil;
        if ([buttonItem.customView isKindOfClass:[UIButton class]]) {
            itemBtn = (UIButton *)buttonItem.customView;
        } else if ([buttonItem.customView isKindOfClass:[UIView class]]) {
            itemBtn = (UIButton *)buttonItem.customView.subviews.firstObject;
        }
        /// 设置button图片/文字偏移
        itemBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -space,0, 0);
        itemBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -space,0, 0);
        itemBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -space,0, 0);
        /// 改变button事件响应区域
        itemBtn.hitEdgeInsets = UIEdgeInsetsMake(0, -space, 0, space);
    }
    for (UIBarButtonItem *buttonItem in viewController.navigationItem.rightBarButtonItems) {
        if (buttonItem.customView == nil) { continue; }
        UIButton *itemBtn = nil;
        if ([buttonItem.customView isKindOfClass:[UIButton class]]) {
            itemBtn = (UIButton *)buttonItem.customView;
        } else if ([buttonItem.customView isKindOfClass:[UIView class]]) {
            itemBtn = (UIButton *)buttonItem.customView.subviews.firstObject;
        }
        itemBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0,0, -space);
        itemBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0,0, -space);
        itemBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0,0, -space);
        itemBtn.hitEdgeInsets = UIEdgeInsetsMake(0, space, 0, -space);
    }
}

2. 改变button的响应区域

此处借鉴UIButton 扩大按钮的响应区域但小编做了些许修改

  • 创建UINavigationBar, 重写- (UIView *)hitTest: withEvent:方法
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
    UIView *view = [super hitTest:point withEvent:event];
    if (point.x<= kScreen_Width * 0.5) {
        for (UIBarButtonItem *buttonItem in self.topItem.leftBarButtonItems) {
            if (buttonItem.customView == nil) { continue; }
            /// 根据实际情况(自己项目UIBarButtonItem的层级)获取button
            UIButton *itemBtn = nil;
            if ([buttonItem.customView isKindOfClass:[UIButton class]]) {
                itemBtn = (UIButton *)buttonItem.customView;
            } else if ([buttonItem.customView isKindOfClass:[UIView class]]) {
                itemBtn = (UIButton *)buttonItem.customView.subviews.firstObject;
            }
            /// 将button的坐标系从父视图转化到UINavigationBar上
            CGRect newRect = [itemBtn convertRect:[itemBtn hitFrame] toView:self];
            /// 如果触摸点在button的响应范围内,让button响应此次触摸事件
            if (CGRectContainsPoint(newRect, point)) {
                view = itemBtn;
                break;
            }
        }
    } else {
        for (UIBarButtonItem *buttonItem in self.topItem.rightBarButtonItems) {
            if (buttonItem.customView == nil) { continue; }
            UIButton *itemBtn = nil;
            if ([buttonItem.customView isKindOfClass:[UIButton class]]) {
                itemBtn = (UIButton *)buttonItem.customView;
            } else if ([buttonItem.customView isKindOfClass:[UIView class]]) {
                itemBtn = (UIButton *)buttonItem.customView.subviews.firstObject;
            }
            CGRect newRect = [itemBtn convertRect:[itemBtn hitFrame] toView:self];
            if (CGRectContainsPoint(newRect, point)) {
                view = itemBtn;
                break;
            }
        }
    }
    return view;
}

PS : 附上demo

你可能感兴趣的:(iOS11适配, 设置自定义导航栏按钮左/右间距为0)