Truncate UILabel text before 5 character of string
Asked Answered
P

2

3

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.

Pavis answered 16/8, 2018 at 9:47 Comment(1)
Yes, find your string and calculate position of 5 character before. And add "\n" at that index. May be its help youCraig
P
1

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
    } 
Pavis answered 20/8, 2018 at 8:15 Comment(0)
F
0

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, suffix: String = ) -> String {
        guard count < self.count else {
            return self
        }
        
        let truncateAfter = index(startIndex, offsetBy: count)
        return String(self[startIndex..<truncateAfter]) + suffix
    }
}
Fulgurous answered 16/8, 2018 at 12:51 Comment(2)
index(startIndex, offsetBy: count) throws error if total character count is less than count value. Just add a guard statement before first line - guard self.count >= count else { return self} let truncateAfter = index(startIndex, offsetBy: count)Sarcoma
@DebashishDas thanks for the catch - looks like that API changed since I wrote this. I have incorporated your feedback.Fulgurous

© 2022 - 2024 — McMap. All rights reserved.