Truncate UILabel text before 5 character of string

2019-07-27 00:04发布

Is it possible to truncate the UILabel text before 5 character of string in autolayout based on the screen size and different device orientation ex.

Test test test test test test...*1234

I know there are several lineBreakMode possible for UILabel like .byTruncatingTail, .byTruncatingMiddle etc. but nothing is working for my case. Any suggestions will be appreciated.

2条回答
Bombasti
2楼-- · 2019-07-27 00:28

Appreciate every once answers and comments above!

So finally I am able to finish it, which is working great in all devices of iPhone and iPad in landscape and portrait mode also split mode in iPad too!

So i would like to share my implementation here:

Step1: Create a TitleView.xib file.

Step2: Took Two Label's Name Label and Number Label.

Step3: Given the following constraints to both the labels:

  • Name Label Constraints:

enter image description here

  • Name Label Line Break : Truncate Tail:

enter image description here

  • Number Label Constraints:

enter image description here

Step4: Then load the xib in viewDidLoad method:

override func viewDidLoad() {
        super.viewDidLoad()
        let titleView = Bundle.main.loadNibNamed("TitleView", owner: self, options: nil)?[0] as! TitleView
        self.navigationItem.titleView = titleView
    } 
查看更多
The star\"
3楼-- · 2019-07-27 00:41

You can do what you're asking pretty elegantly by juggling string indexes. If you're planning to do this in a few places in your code, consider creating an extension on String, to make it easier to reuse. Also consider using an ellipsis () instead of just three periods.

extension String {

    func truncated(after count: Int) -> String {
        let truncateAfter = index(startIndex, offsetBy: count)
        guard endIndex > truncateAfter else { return self }
        return String(self[startIndex..<truncateAfter]) + "…"
    }
}

Try it yourself

查看更多
登录 后发表回答