最近在自己练手的APP中遇到自定义导航栏上移的问题,参考了诸多大神的帖子,最后自己整理一下iOS11自定义导航栏上移问题的解决方法。先来看下问题截图:
1、导航栏出现的问题
出现的问题解决后图片:
解决后图片2、解决方法,归根到底就是iOS11系统的导航栏图层发生变化,遍历View,修改frame,新建继承navigationbar的类,重写layoutsubviews方法,isiPhoneX为判断iPhone X宏,直接上代码:
OC代码:
- (void)layoutSubviews {
[super layoutSubviews];
#ifdef __IPHONE_11_0
if (@available(iOS 11.0, *)) {
for (UIView *view in self.subviews) {
if([NSStringFromClass([view class]) containsString:@"Background"]) {
view.frame = self.bounds;
}
else if ([NSStringFromClass([view class]) containsString:@"ContentView"]) {
CGRect frame = view.frame;
frame.origin.y = isiPhoneX ? 44 : 20;
frame.size.height = self.bounds.size.height - frame.origin.y;
view.frame = frame;
}
}
}
#endif
}
Swift代码:
override func layoutSubviews() {
super.layoutSubviews()
for subview in subviews {
let subName = NSStringFromClass(subview.classForCoder)
if subName == "_UIBarBackground" {
subview.frame = bounds
}else if subName == "_UINavigationBarContentView" {
var frame = subview.frame;
frame.origin.y = isiPhoneX ? 44 : 20
frame.size.height = self.bounds.size.height - frame.origin.y;
subview.frame = frame;
}
}
}
如有问题请沟通。
网友评论