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