[英]UILabel in UINavigationBar is cut off in landscape
Swift 5,Xcode 10.2
我想在UINavigationBar
顯示兩行文本,這就是為什么我使用UILabel
的原因:
@IBOutlet weak var navigationBar: UINavigationItem!
override func viewDidLoad() {
let labeltext = NSMutableAttributedString.init(string: "Text in line 1\n(Line 2)")
labeltext.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)],range: NSRange(location: labeltext.length-8, length: 8))
let label = UILabel()
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 17.0)
label.textAlignment = .center
label.textColor = .black
label.attributedText = labeltext
navigationBar.titleView = label
}
縱向顯示如下:
在較小的設備上,文字會橫向剪切(在iPhone Xs Max和iPad上很好):
我試圖按照此處的建議擴展UINavigationBar
:
extension UINavigationBar {
open override func sizeThatFits(_ size: CGSize) -> CGSize {
let portraitSize = CGSize(width: UIScreen.main.bounds.width, height: 44)
return portraitSize
}
}
...但沒有進行任何更改並print("Navigationbar height: \\(navigationController!.navigationBar.frame.height)")
始終顯示“ 44”,無論它的方向和使用的設備是什么(即使在iPhone X)。
按照此處的建議添加觀察者也無濟於事。
我如何解決此問題以顯示2行代碼,同時又不破壞較大的設備/帶有槽口的設備呢?
我沒有找到使UINavigationBar
顯示兩行文本或增加其高度的方法(我在問題中發布的擴展名沒有任何作用)。 相反,我現在使用此代碼根據設備和設備方向更改標簽:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if (UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight) && UIDevice.current.userInterfaceIdiom == .phone {
//1 line: iPhone & horizontal (the NavigationBar on iPads is tall enought to display 2 lines!)
navigationBar.titleView = labelLandscape!
} else {
//2 lines: Vertical (device doesn't matter)
navigationBar.titleView = labelPortrait!
}
}
標簽示例:
//let labelTextPortrait = NSMutableAttributedString.init(string: "Text in line 1\n(Line 2)")
let labelTextLandscape = NSMutableAttributedString.init(string: "Text in line 1 (Line 2)")
labelTextLandscape.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)],range: NSRange(location: labeltextQuer.length-8, length: 8))
//Text size of "(Line 2)" is 8, the remaining text uses 14
var labelLandscape = UILabel()
labelLandscape!.backgroundColor = .clear
labelLandscape!.numberOfLines = 1 //labelPortrait!.numberOfLines = 2
labelLandscape!.font = UIFont.boldSystemFont(ofSize: 17.0)
labelLandscape!.textAlignment = .center
labelLandscape!.textColor = .black
labelLandscape!.attributedText = labelTextLandscape
labelLandscape!.lineBreakMode = .byWordWrapping //important, so it doesn't truncate mid-text!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.