UILabel text truncation vs. line breaks in text

2020-01-29 21:08发布

I have a UILabel that is put as titleView in the navigation bar. I want it to have 2 lines, where the first line can be truncated and the second is center aligned.

In code it looks more less like this:

    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

The effect in case of the first line text is not exceeding available space is like this:

enter image description here

It's pretty good, but when the first line text is longer than:

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

enter image description here

I want to achieve like below.

enter image description here

How it can be done? I experimented with numberOfLines and lineBreakMode but it's not worked.

2条回答
叼着烟拽天下
2楼-- · 2020-01-29 21:16

change your line breakmode to ByTruncatingMiddle instead of ByTruncatingTail. Something like below,

    label.lineBreakMode = .ByTruncatingMiddle

Hope this will help :)

查看更多
淡お忘
3楼-- · 2020-01-29 21:27

Navigation Tittle with sub-Tittle (Multiline Navigation Tittle)

Use NSMutableAttributedString with UITextView instead of UILabel

(because, if tittle is large then UILabel lineBreakMode with .byTruncatingTail is not working for first line in 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
    }
}
查看更多
登录 后发表回答