最近在自己練手的APP中遇到自定義導(dǎo)航欄上移的問題,參考了諸多大神的帖子全肮,最后自己整理一下iOS11自定義導(dǎo)航欄上移問題的解決方法。先來看下問題截圖:
1、導(dǎo)航欄出現(xiàn)的問題
解決后圖片:
2趾代、解決方法,歸根到底就是iOS11系統(tǒng)的導(dǎo)航欄圖層發(fā)生變化丰辣,遍歷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;
}
}
}
如有問題請溝通得湘。