参考:贝聊科技的这篇文章
直奔主题
自定义UIBarButtonItem
的CustomView
.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];
我这里是设置的rightBarButtonItems
,leftBarButtonItems
需要设置这里
_customBarButtonView.alignmentRectInsetsOverride = UIEdgeInsetsMake(0, -10, 0, 10);
效果图
网友评论