iOS 10自定义导航栏高度

前端之家收集整理的这篇文章主要介绍了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)
    }
}

猜你在找的iOS相关文章