我有一个UILabel,在导航栏中作为titleView放置。我希望它有2行,第一行可以截断,第二行是中心对齐。
在代码中,它看起来更像是这样:
let label = UILabel()
let text = NSAttributedString(string: "Long long long text\nsecond line")
label.attributedText = text
label.textAlignment = .Center
label.numberOfLines = 0
label.lineBreakMode = .ByTruncatingTail
label.sizeToFit()
self.navigationItem.titleView = label
到目前为止一切顺利。
第一行文字较长时出现问题:
let text = NSAttributedString(string: "Very very very very very long text\nsecond line")
我想要达到的目标是:
知道如何做到这一点?我尝试使用numberOfLines和lineBreakMode但没有令人满意的结果。
答案 0 :(得分:1)
将您的换行符更改为ByTruncatingMiddle
而不是ByTruncatingTail
。如下所示,
label.lineBreakMode = .ByTruncatingMiddle
希望这会有所帮助:)
答案 1 :(得分:0)
带子标题的导航标题(多行导航标题)
使用NSMutableAttributedString和 UITextView 代替 UILabel
(因为如果标题是大,则带有.byTruncatingTail的 UILabel lineBreakMode 不适用于第一行在UILabel中)
func multilineNavigation(title:String,subTitle:String) {
DispatchQueue.main.async {
let titleAttributedStr = NSMutableAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 17.0) ?? UIFont()])
let subTitleAttributedStr = NSMutableAttributedString(string: "\n\(subTitle)", attributes: [NSAttributedStringKey.foregroundColor: UIColor.green,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 12.0) ?? UIFont()])
titleAttributedStr.append(subTitleAttributedStr)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1
paragraphStyle.lineBreakMode = .byTruncatingTail
titleAttributedStr.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, titleAttributedStr.length))
let textView = UITextView()
textView.attributedText = titleAttributedStr
textView.backgroundColor = .clear
textView.isUserInteractionEnabled = false
textView.textContainerInset = .zero
textView.textAlignment = .center
textView.frame = CGRect(x: 0, y: 0, width: textView.intrinsicContentSize.width, height: 44)
self.navigationItem.titleView = textView
}
}