override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let height = CGFloat(84)
self.navigationController?.navigationBar.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: height)
}
此代码只是在titleView上方插入空格。点(0,0)处的自定义titleView在其上方有大约20个点。高度> 40开始从navBar运行。
答案 0 :(得分:2)
您可以使用自定义视图替换导航栏。这更加简单灵活。隐藏导航栏并实现自定义视图。
class ViewController : UIViewController {
var navBar: UINavigationBar = UINavigationBar()
override func viewDidLoad() {
super.viewDidLoad()
self.setCustomNavBarView()
}
func setCustomNavBarView() {
self.navBar.frame = CGRect(x: 0, y: 0, width: 350, height: 50) // Set you custom width and Height
self.navBar.backgroundColor = UIColor.gray
self.view.addSubview(navBar)
}
}
关于如何做到这一点的简单tutorial:
希望这会有所帮助!!
答案 1 :(得分:1)
您可以继承UINavigationBar:
class CustomNavigationBar: UINavigationBar {
override func sizeThatFits(_ size: CGSize) -> CGSize {
let newSize :CGSize = CGSize(width: self.frame.size.width,height: 84)
return newSize
}
}
然后创建导航控制器并使用初始化程序来使用自定义导航栏类。
let nav = UINavigationController(navigationBarClass:CustomNavigationBar.self,toolbarClass: nil)
保留UINavigationBar的所有现有行为,并采用您的自定义高度。
OR
就像你已经尝试过的那样:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let height: CGFloat = 84 //whatever height you want
let bounds = self.navigationController!.navigationBar.bounds
self.navigationController?.navigationBar.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height + height)
}
或者: 您可以尝试此解决方案Changing the height of the Navigation bar iOS Swift
答案 2 :(得分:0)
class ViewController: UIViewController {
var navBar: UINavigationBar = UINavigationBar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setCustomNavBarView()
}
`func setCustomNavBarView() {
self.navBar.frame = CGRect(x: 0, y: 0, width: 350, height: 100) // Set you custom width and Height
self.navBar.backgroundColor = UIColor.gray
self.view.addSubview(navBar)
}
`
swift 3更新了代码