如何知道最后一行标签的宽度?

How to know the width of last line of label?

在我的应用程序中,我有一个文本来自服务器的标签,所以我不知道它的宽度,在这个标签的末尾直接应该有一个 UIImage。

我的问题是:由于标签文本的非静态宽度,我不知道如何定位图像。

更清楚地说,这是设计的快照,它应该是怎样的:

有什么解决这个问题的建议吗?

实际上,这取决于...

您可能想要使用 sizeToFitsizeThatFits 方法。

您可以直接在标签上插入图片

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
  1. 设置 UILabel
  2. 的文本
  3. yourUILabel得到这个UILabel的宽度。frame.width
  4. 像这样将 UIImage 的 x 坐标设置为 yourUILabel.frame.width + emptySpace

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

我设法解决了这个问题。这不是最漂亮的代码,但它可以工作。我 return 标签最后一行的字数,我可以从中计算文本结束处和图像开始处的宽度 (x,y) 坐标。

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
}