[英]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.是否可以根据屏幕大小和不同的设备方向在自动布局中截断字符串的 5 个字符之前的 UILabel 文本。
Test test test test test test...*1234
测试测试测试测试测试测试...*1234
I know there are several lineBreakMode
possible for UILabel
like .byTruncatingTail, .byTruncatingMiddle etc.
but nothing is working for my case.我知道
UILabel
有几种lineBreakMode
可能,例如.byTruncatingTail, .byTruncatingMiddle etc.
但对我的情况没有任何作用。 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!所以最后我能够完成它,这在
iPhone
和iPad
所有设备上都非常有效, landscape
和portrait
模式也可以在 iPad 中使用split mode
!
So i would like to share my implementation here:所以我想在这里分享我的实现:
Step1: Create a TitleView.xib file.第一步:创建一个 TitleView.xib 文件。
Step2: Took Two Label's Name Label
and Number Label
. Step2:取两个标签的
Name Label
和Number Label
。
Step3: Given the following constraints to both the labels:步骤 3:给定以下两个标签的约束:
Step4: Then load the xib in viewDidLoad
method: Step4:然后在
viewDidLoad
方法中加载xib:
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.如果您计划在代码中的几个地方执行此操作,请考虑在
String
上创建extension
,以使其更易于重用。 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]) + "…"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.