UILabel truncate tail and skip not complete word

社会主义新天地 提交于 2019-12-30 09:29:43

问题


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

You have 30 seconds to make an impression during an interview

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

self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;

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.


回答1:


You can do something like this:

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




回答2:


i am not sure but try it:

nameLabel.adjustsFontSizeToFitWidth = NO;
nameLabel.lineBreakMode = NSLineBreakByWordWrapping;

OR

If you are using storyboard follow these steps i tried this and it working fine

  • Open Attribute Inspector
  • Change Line Breaks to Truncate Tail then

  • Change AutoShrink to Minimum Font Size

here are my screenshots of label after and before applying these properties

new output




回答3:


Ideally this is not possible,with default UILabel, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter/word the OS will truncate it, one solution to fix the issue you can use following properties depending on your match.

Minimum Font Scale -- Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.

Minimum Font Size -- When drawing text that might not fit within the bounding rectangle of the label, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.



来源:https://stackoverflow.com/questions/37410288/uilabel-truncate-tail-and-skip-not-complete-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!