Is there a way to make a two line prompt for a swift navigation bar? I currently cannot find a property to modify. The text I am currently displaying in the prompt comes from an external data model, so sometimes there is more text than fits on the screen. Thanks.
You can try like this:
Swift 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
Navigation bar has a title and a prompt
navigationItem.title = "Title, large"
navigationItem.prompt = "One line prompt, small text, auto-shrink"
Having a prompt could be better that having a custom title view, because it gives you more height and it works great with searchbars. But make sure this is really what you want, since the code bellow is not tested on all devices iOS versions. This will just give you an idea how you can control almost anything regarding layout in the navigation bar
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)
}
}
To use your navigation bar use:
let navVc = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: nil)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.