在我的應用程序中,我有一個標籤,其中的文本來自服務器,所以我不知道它的寬度,並且在該標籤的末尾直接應該有一個UIImage。如何知道最後一行標籤的寬度?
我的問題是:我不知道如何定位圖像,因爲標籤文本的非靜態寬度。
更清楚,這是一個快照,形成設計,應該如何:
任何建議來解決這個問題嗎?
在我的應用程序中,我有一個標籤,其中的文本來自服務器,所以我不知道它的寬度,並且在該標籤的末尾直接應該有一個UIImage。如何知道最後一行標籤的寬度?
我的問題是:我不知道如何定位圖像,因爲標籤文本的非靜態寬度。
更清楚,這是一個快照,形成設計,應該如何:
任何建議來解決這個問題嗎?
UILabel
UILabel
的寬度與yourUILabel
.frame.width將UIImage
的x座標設置爲yourUILabel.frame.width + emptySpace
像這樣
var yourUIImageView:UIImageView = UIImageView(frame: CGRectMake(x:PaddingFromLeft + yourUILabel.frame.width + emptySpace, y: yourYCoordinate, width: yourImageWidth, height : yourImageHeight))
您可以直接標籤上插入圖像這樣
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
非常感謝! 這是驚人的:) 但我可以調整附件大小? ,因爲圖像看起來很大 – Rawan
@eng_rawan:我會說最好的將得到與您的場景的大小正確的圖像 –
我設法解決了這個問題。這不是最漂亮的代碼,但它的工作原理。我從標籤的最後一行返回單詞數字,從中我可以計算出文本結束處的寬度以及圖像開始(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
}
我會建議使用字體符號。可以說你的字符串是屬性字符串,只需在末尾添加► 黑色右指針 Unicode:U + 25BA,UTF-8:E2 96 BA。並把它變成藍色,你就完成了。 –
我可以爲它着色嗎? ,因爲你可以看到它是藍色的 – Rawan
@JurajAntas我的字符串來自服務器,所以我可以在這裏使用你的想法? 非常感謝:) – Rawan