iOS11修复导航栏按钮位置偏移问题
2021-03-15 本文已影响0人
帅聪哥
iOS11后,系统更改了UINavigationBar的布局结构,所以会导致自定义导航按钮的位置会便的很离谱。现在推荐一个简单方法:
有两种方法:
1、如果是全局通用,则使用扩展,
@implementation UINavigationBar (BDFixSpace)
+(void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method originalMethodImp = class_getInstanceMethod(self, @selector(layoutSubviews));
Method destMethodImp = class_getInstanceMethod(self, @selector(bd_layoutSubviews));
method_exchangeImplementations(originalMethodImp, destMethodImp);
});
}
-(void)bd_layoutSubviews{
[self bd_layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:@"_UINavigationBarContentView"]) {
UIEdgeInsets margins = subview.layoutMargins;
if(CURRENT_VERSION >= 11.0){
subview.frame = CGRectMake(-margins.left*0.5, -margins.top, margins.left*0.5 + margins.right*0.5 + subview.frame.size.width, margins.top + margins.bottom + subview.frame.size.height);
}else{
margins = UIEdgeInsetsZero;
}
break;
}
}
}
2、如果是自定义navigationbar,则重写layoutsubview方法即可
-(void)layoutSubviews{
[self layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:@"_UINavigationBarContentView"]) {
UIEdgeInsets margins = subview.layoutMargins;
if(CURRENT_VERSION >= 11.0){
subview.frame = CGRectMake(-margins.left*0.5, -margins.top, margins.left*0.5 + margins.right*0.5 + subview.frame.size.width, margins.top + margins.bottom + subview.frame.size.height);
}else{
margins = UIEdgeInsetsZero;
}
break;
}
}
}
是不是很简单!
谢谢,如果帮到你还请点个赞哈!