自定义UINavigationBar不遵循给定的高度

时间:2018-11-13 10:35:54

标签: ios swift uinavigationcontroller uinavigationbar

我有一个自定义UINavigationBar,称为MapNavBar。此类声明如下:

class MapNavBar: UINavigationBar {

override func sizeThatFits(_ size: CGSize) -> CGSize {
    let screenSize = UIScreen.main.bounds.size
    let landscape = screenSize.width > screenSize.height
    if landscape {
        let navBarHeight: CGFloat = 44.0
        return CGSize(width: screenSize.width, height: navBarHeight)
    }
    return super.sizeThatFits(size)
}

}

自定义导航栏被分配给导航控制器,如下所示:

navController.setValue(MapNavBar(), forKeyPath : "navigationBar")

现在,当方向更改为横向时,我希望将导航栏的高度保持为标准的(纵向)高度44。因此,在MapController viewWillLayoutSubviews中,我这样做:

override func viewWillLayoutSubviews() {

    if let navController = ... {
        let screenSize = UIScreen.main.bounds.size
        let landscape = screenSize.width > screenSize.height
        if landscape {
            let navBarHeight = navController.navigationBar.sizeThatFits(screenSize).height

            // Resize navBar
            navController.navigationBar.frame = CGRect(x: 0, y: 0, width: Int(screenSize.width), height: Int(navBarHeight))
        }
    }
    super.viewWillLayoutSubviews()
}

尽管进行了所有努力,但自定义导航栏的高度在横向时仍保持在32点。我已经检查过,导航控制器的navigationBar属性确实是我的自定义MapNavBar的实例。

有人知道为什么会这样以及如何解决吗?

谢谢

1 个答案:

答案 0 :(得分:1)

尝试一下:

class MapNavBar: UINavigationBar {

    let navBarHeight: CGFloat = 64 //44 + 20 Where 20 is for status bar, it is hidden in landscape mode always

    override func sizeThatFits(_ size: CGSize) -> CGSize {

        let frame = self.frame
        let screenSize = UIScreen.main.bounds.size
        let landscape = screenSize.width > screenSize.height
        if landscape {
            return CGSize(width: frame.width, height: navBarHeight)
        }
        return super.sizeThatFits(size)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let screenSize = UIScreen.main.bounds.size
        let landscape = screenSize.width > screenSize.height
        if landscape {
            let y = UIApplication.shared.statusBarFrame.height
            frame = CGRect(x: frame.origin.x, y:  y, width: frame.size.width, height: navBarHeight)

            for subview in self.subviews {
                var stringFromClass = NSStringFromClass(subview.classForCoder)
                if stringFromClass.contains("BarBackground") {
                    subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: navBarHeight)
                    subview.backgroundColor = self.backgroundColor
                }

                stringFromClass = NSStringFromClass(subview.classForCoder)
                if stringFromClass.contains("BarContent") {
                    subview.frame = CGRect(x: subview.frame.origin.x, y: 0, width: subview.frame.width, height: navBarHeight)
                    subview.backgroundColor = self.backgroundColor
                }
            }
        }
    }
}

enter image description here