How to know the width of last line of label?

与世无争的帅哥 提交于 2019-12-13 01:27:47

问题


In my app I have a label which text came from the server so I don't Know its width, and at the end of this label directly there should be an UIImage.

My problem is: I don't know how to position the image because of the non static width of the label text.

To be more clear, this is a snapshot form the design and how should it be:

Any suggestion to solve this problem please?


回答1:


  1. Set the text of the UILabel
  2. Get the width of this UILabel with yourUILabel.frame.width
  3. Set the x coordinate of your UIImage at yourUILabel.frame.width + emptySpace like this

    var yourUIImageView:UIImageView = UIImageView(frame: CGRectMake(x:PaddingFromLeft + yourUILabel.frame.width + emptySpace, y: yourYCoordinate, width: yourImageWidth, height : yourImageHeight))
    



回答2:


You may be able to insert your image directly on label doing this

var attachment = NSTextAttachment()
attachment.image = UIImage(named: "your_image_name")

var attributedString = NSAttributedString(attachment: attachment)
var labelString= NSMutableAttributedString(string: "Lorem ipsum dolor sit ame...")
labelString.appendAttributedString(attributedString)

yourUILabel.attributedText = labelString



回答3:


I managed to solve this problem. It's not the most beautiful code but it works. I return the words number from the last line of the label, from which I can calculate the width from where the text ends and the image starts (x,y) coordinates.

func lastWordInTitle(title: String) -> Int {
    var separateWords: [String] = []
    var sizeOfWords: [CGFloat] = []
    var wordsRemaining: Int = 0
    var wordsWidthInOneLine: CGFloat = 0

    let font = titleLabel.font
    let fontAttr = [NSAttributedStringKey.font: font]

    title.enumerateSubstrings(in: title.startIndex..<title.endIndex, options: .byWords) { (substring, _, _, _) in
        if let substring = substring {
            separateWords.append(substring) // number of words in label
            sizeOfWords.append(substring.size(withAttributes: fontAttr).width + 8) //size of each word + 8 for the space between them
        }
    }
    wordsRemaining = separateWords.count
    print("SSS wordsRemaining initial \(wordsRemaining)")
    var wordsToRemoveIndex = 0

    for index in 0..<separateWords.count {
        wordsWidthInOneLine += sizeOfWords[index]
        wordsToRemoveIndex += 1
        if wordsWidthInOneLine > titleLabel.frame.width {
            if index == separateWords.count - 1  {
                wordsRemaining -= wordsToRemoveIndex
                return 1
            } else {
                wordsRemaining -= wordsToRemoveIndex - 1 == 0 ? 1 : wordsToRemoveIndex - 1
                wordsToRemoveIndex = 0
                wordsWidthInOneLine = 0
                wordsWidthInOneLine = sizeOfWords[index]

            }
        } else if wordsWidthInOneLine < titleLabel.frame.width && index == separateWords.count - 1 {
            let reversedSeparateWordsSize = Array(sizeOfWords.reversed())
            var width: CGFloat = 0
            for index in 0..<wordsRemaining {
                width += reversedSeparateWordsSize[index]
            }
            if width > titleLabel.frame.width {
                return wordsRemaining - 1
            }
            return wordsRemaining
        }
    }

    return wordsRemaining
}



回答4:


It, actually, depends...

You might want to use sizeToFit or sizeThatFits methods.



来源:https://stackoverflow.com/questions/30351076/how-to-know-the-width-of-last-line-of-label

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