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

时间:2015-05-20 13:26:59

标签: ios iphone swift uilabel

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

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

更清楚的是,这是设计的快照,应该如何:

snapshot

有任何解决这个问题的建议吗?

4 个答案:

答案 0 :(得分:3)

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

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 :(得分:1)

我设法解决了这个问题。它不是最漂亮的代码,但它有效。我从标签的最后一行返回单词数字,我可以从中计算文本结束的宽度,图像开始(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
}

答案 2 :(得分:0)

实际上,它取决于...

您可能希望使用sizeToFitsizeThatFits方法。

答案 3 :(得分:0)

  1. 设置UILabel
  2. 的文字
  3. 使用UILabel。frame.width
  4. 获取此yourUILabel的宽度
  5. UIImage的x坐标设置为yourUILabel.frame.width + emptySpace,如此

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