Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

ios - UILabel text truncation vs. line breaks in text

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
second 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
second 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

    label.lineBreakMode = .ByTruncatingMiddle

Hope this will help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...