Không ai trong số các giải pháp đường may trên để làm việc đáng tin cậy đối với tôi. Tuy nhiên tôi đã tìm thấy một giải pháp bằng cách sử dụng các yếu tố khác nhau để cung cấp câu trả lời, trong Swift 2 và thực sự thanh lịch vì không yêu cầu bất kỳ mã tùy chỉnh nào mỗi khi bạn thay đổi nhãn, nó chỉ sử dụng các nhà quan sát thuộc tính trên tiêu đề. Lưu ý rằng trong trường hợp của tôi, tôi đã có một nút quay lại ở phía bên trái của thanh điều hướng, mà putted văn bản ra khỏi trung tâm của màn hình, để sửa lỗi này tôi đang sử dụng văn bản được phân bổ và tailIndent. Tất cả các ý kiến / thông tin trong đoạn code dưới đây:
class VCHowToTopic : UIViewController {
//add handlers so that any manipulation of the title is caught and transferred to the custom drawn UILabel
override var title : String? {
set {
super.title = newValue
configureTitleView()
}
get {
return super.title
}
}
//MARK: - lifecycle
func configureTitleView() {
//some large number that makes the navigationbar schrink down our view when added
let someVeryLargeNumber = CGFloat(4096)
//create our label
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: someVeryLargeNumber, height: someVeryLargeNumber))
//0 means unlimited number of lines
titleLabel.numberOfLines = 0
//define style of the text (we will be using attributed text)
let style = NSMutableParagraphStyle()
style.alignment = .Center
//top compensate for the backbutton which moves the centered text to the right side of the screen
//we introduce a negative tail indent, the number of 56 has been experimentally defined and might
//depend on the size of your custom back button (if you have one), mine is 22x22 px
style.tailIndent = -56
//create attributed text also with the right color
let attrText = NSAttributedString(string: title!, attributes: [NSParagraphStyleAttributeName : style,
NSForegroundColorAttributeName : UIColor.whiteColor()])
//configure the label to use the attributed text
titleLabel.attributedText = attrText
//add it as the titleview
navigationItem.titleView = titleLabel
}
}
Kiểm tra liên kết này http://stackoverflow.com/questions/2422383/uinavigationbar-multi-line-title Nó sẽ giải quyết vấn đề của bạn hy vọng. – gopal