简体   繁体   中英

Truncate UILabel text before 5 character of string

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.

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:

在此处输入图片说明

  • Name Label Line Break : Truncate Tail:

在此处输入图片说明

  • Number Label Constraints:

在此处输入图片说明

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
    } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM