gpt4 book ai didi

ios - 自定义 UINavigationBar 不支持给定的高度

转载 作者:可可西里 更新时间:2023-11-01 01:56:09 26 4
gpt4 key购买 nike

我有一个自定义的 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)
}

自定义导航栏分配给导航 Controller ,如下所示:

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 点。我已经检查过,导航 Controller 的 navigationBar 属性确实是我的自定义 MapNavBar 的一个实例。

有谁知道为什么会发生这种情况以及如何解决它?

谢谢

最佳答案

试试这个:

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

关于ios - 自定义 UINavigationBar 不支持给定的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53279094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com