iOS 10自定义导航栏高度

我使用下面的代码实现了自定义导航栏高度

class TMNavigationBar: UINavigationBar { ///The height you want your navigation bar to be of static let navigationBarHeight: CGFloat = 44.0 ///The difference between new height and default height static let heightIncrease:CGFloat = navigationBarHeight - 44 override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { let shift = TMNavigationBar.heightIncrease/2 ///Transform all view to shift upward for [shift] point self.transform = CGAffineTransformMakeTranslation(0, -shift) } override func layoutSubviews() { super.layoutSubviews() let shift = TMNavigationBar.heightIncrease/2 ///Move the background down for [shift] point let classNamesToReposition: [String] = ["_UINavigationBarBackground"] for view: UIView in self.subviews { if classNamesToReposition.contains(NSStringFromClass(view.dynamicType)) { let bounds: CGRect = self.bounds var frame: CGRect = view.frame frame.origin.y = bounds.origin.y + shift - 20.0 frame.size.height = bounds.size.height + 20.0 view.frame = frame } } } override func sizeThatFits(size: CGSize) -> CGSize { let amendedSize:CGSize = super.sizeThatFits(size) let newSize:CGSize = CGSizeMake(amendedSize.width, TMNavigationBar.navigationBarHeight); return newSize; } } 

以下问题仅在iOS 10上出现:(黑条和视图之间的空白)

在这里输入图像说明

不知道那里发生了什么。 但在故事板中,它产生了这个警告,并且没有办法在IB中修复它(警告只出现在我更改IB中导航栏的子类时出现)。

在这里输入图像说明

适用于iOS 10,Swift 3.0:

 extension UINavigationBar { open override func sizeThatFits(_ size: CGSize) -> CGSize { let screenRect = UIScreen.main.bounds return CGSize(width: screenRect.size.width, height: 64) } } 

我检查了接口debugging器,这就是我看到的(所以基本上它试图改变导航栏的高度,它保持不变,它显示的只是黑色的空间 – 这是窗口的颜色):

在这里输入图像说明

随着后来的调查,我注意到它不是调用:“ _UINavigationBarBackground

然后我检查快速枚举view.classForCoder,并发现密钥更改为“ _UIBarBackground ”,所以我更新了layoutSubviews():

 override func layoutSubviews() { super.layoutSubviews() let shift = TMNavigationBar.heightIncrease/2 ///Move the background down for [shift] point let classNamesToReposition = isIOS10 ? ["_UIBarBackground"] : ["_UINavigationBarBackground"] for view: UIView in self.subviews { if classNamesToReposition.contains(NSStringFromClass(view.classForCoder)) { let bounds: CGRect = self.bounds var frame: CGRect = view.frame frame.origin.y = bounds.origin.y + shift - 20.0 frame.size.height = bounds.size.height + 20.0 view.frame = frame } } } 

干杯。