UILabel文本截断与文本中的换行符

时间:2016-05-24 09:18:25

标签: ios swift uilabel

我有一个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

第一行文字未超出可用空间时的效果如下:enter image description here

到目前为止一切顺利。

第一行文字较长时出现问题:

let text = NSAttributedString(string: "Very very very very very long text\nsecond line")

效果: enter image description here

我想要达到的目标是:

enter image description here

知道如何做到这一点?我尝试使用numberOfLines和lineBreakMode但没有令人满意的结果。

2 个答案:

答案 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
    }
}