你可以这样尝试:
斯威夫特3.0
let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:50)) //width is subject to change, Defined as per your screen
label.backgroundColor =.clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor.white
label.text = "Your Text here"
self.navigationItem.titleView = label
导航栏有标题和提示
navigationItem.title = "Title, large"
navigationItem.prompt = "One line prompt, small text, auto-shrink"
有一个提示可能比有一个自定义标题视图更好,因为它给你更多的高度,并且它与搜索栏配合得很好。但请确保这确实是您想要的,因为下面的代码并未在所有设备 iOS 版本上进行测试。这只会让您了解如何控制导航栏中几乎所有有关布局的内容
class MyNavigationBar: UINavigationBar {
func allSubViews(views: [UIView]) {
for view in views {
if let label = view as? UILabel, label.adjustsFontSizeToFitWidth {
if label.numberOfLines != 2 { //this is the promp label
label.numberOfLines = 2
let parent = label.superview
parent?.frame = CGRect(x: 0, y: 0, width: parent!.bounds.width, height: 44)
parent!.removeConstraints(parent!.constraints)
label.removeConstraints(label.constraints)
label.leadingAnchor.constraint(equalTo: parent!.leadingAnchor, constant: 20).isActive = true
label.trailingAnchor.constraint(equalTo: parent!.trailingAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: parent!.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: parent!.bottomAnchor).isActive = true
}
return
}
self.allSubViews(views: view.subviews)
}
}
override func layoutSubviews() {
super.layoutSubviews()
allSubViews(views: self.subviews)
}
}
要使用导航栏,请使用:
let navVc = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: nil)
您可以将提示配置为多行,如下图所示。诀窍是搜索 UINavigationBar 的所有子视图并以某种方式找到提示视图。执行此操作的一种方法是首先使用一些众所周知的文本加载提示,然后在子视图中搜索该众所周知的文本。在我的示例代码中,我在搜索之前将“默认提示”存储在 navigationItem.prompt 中。
func findPromptView( view: UIView )
{
for item in view.subviews {
if let label = item as? UILabel {
if let text = label.text {
print(text)
if (text == "Default Prompt") {
label.numberOfLines = 2
label.textAlignment = .center
}
}
}
if item.subviews.count > 0 {
findPromptView( view: item )
}
}
}
if let navBar = navigationController?.navigationBar {
navigationItem.prompt = "Default Prompt"
findPromptView( view: navBar)
}