简体   繁体   English

在字符串的 5 个字符之前截断 UILabel 文本

[英]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!所以最后我能够完成它,这在iPhoneiPad所有设备上都非常有效, landscapeportrait模式也可以在 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 LabelNumber Label

Step3: Given the following constraints to both the labels:步骤 3:给定以下两个标签的约束:

  • Name Label Constraints:名称标签约束:

在此处输入图片说明

  • Name Label Line Break : Truncate Tail:名称标签换行符:截尾:

在此处输入图片说明

  • Number Label Constraints:数字标签约束:

在此处输入图片说明

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]) + "…"
    }
}

Try it yourself自己试试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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