美文网首页
解决iOS11NavigationItem的UIBarButto

解决iOS11NavigationItem的UIBarButto

作者: HappyJiuOk | 来源:发表于2019-09-30 16:09 被阅读0次

参考:贝聊科技的这篇文章

直奔主题

自定义UIBarButtonItemCustomView

.h
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface BarButtonCustomView : UIView

@property (nonatomic) UIEdgeInsets alignmentRectInsetsOverride;

@end

NS_ASSUME_NONNULL_END

.m
@implementation BarButtonCustomView
- (UIEdgeInsets)alignmentRectInsets {
    if (UIEdgeInsetsEqualToEdgeInsets(self.alignmentRectInsetsOverride,UIEdgeInsetsZero)) {
        return super.alignmentRectInsets;
    } else {
        return self.alignmentRectInsetsOverride;
    }
    
}
@end

使用方法:

    _customBarButtonView = [[BarButtonCustomView alloc] init];
    _customBarButtonView.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
/*  UIEdgeInsetsMake(0, -10, 0, 10);根据自己需要  */
        _customBarButtonView.alignmentRectInsetsOverride = UIEdgeInsetsMake(0, -10, 0, 10);
        _customBarButtonView.translatesAutoresizingMaskIntoConstraints = NO;
/*  100宽度根据自己需要  */
        [_customBarButtonView.widthAnchor constraintEqualToConstant:100].active = YES;
        [_customBarButtonView.heightAnchor constraintEqualToConstant:44].active = YES;
    }
    //ios 11之前(我项目最低支持iOS10)下边的方式有效。
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_customBarButtonView];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,item];

我这里是设置的rightBarButtonItemsleftBarButtonItems需要设置这里
_customBarButtonView.alignmentRectInsetsOverride = UIEdgeInsetsMake(0, -10, 0, 10);
效果图

rightBarButtonItems 加颜色看看

相关文章

网友评论

      本文标题:解决iOS11NavigationItem的UIBarButto

      本文链接:https://www.haomeiwen.com/subject/kyqhpctx.html