UILabel截尾并跳过未完成的单词 [英] UILabel truncate tail and skip not complete word

查看:63
本文介绍了UILabel截尾并跳过未完成的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一行UILabel.它的宽度=屏幕宽度,现在的内容是(UILabel的内容可以更改)

I have a single line UILabel. It has width = screen width and the content now is (the content of UILabel can change)

您在采访中有30秒的印象

You have 30 seconds to make an impression during an interview

当前,我的UILabel是尾部截断的,并且持续时间" 这个词不完整

Currently, my UILabel is truncated tail and the word "duration" is not complete

self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;

我想要的是我希望我的UILabel 静止截尾巴,并且显示完整的单词.
就像下面的图片

What I want is I want my UILabel still truncating tail and only display complete word.
Like the image below

任何帮助或建议将不胜感激.

Any help or suggestion would be great appreciated.

推荐答案

您可以执行以下操作:

let labelWidth = CGRectGetWidth(label.bounds)

    let str = "You will have 30 seconds till you give us a good impression" as NSString
    let words = str.componentsSeparatedByString(" ")

    var newStr = "" as NSString

    for word in words{

        let statement = "\(newStr) \(word) ..." as NSString
        let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
        if size.width < labelWidth {
            newStr = "\(newStr) \(word)"
        }
        else{
           break
        }
    }

    newStr = newStr.stringByAppendingString(" ...")

    self.label.text = newStr as String

想法是:我们拆分单词并尝试检查宽度,同时从头开始添加+字符串"...",直到找到一个超出大小的单词,以防我们停止并使用此新字符串

Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string

这篇关于UILabel截尾并跳过未完成的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆