当我的标签文本超过 3 行时,我想将此文本“...阅读更多”,我想防止我的文本不会被截断。
我尝试了一些代码,但在使用不同的 iPhone 宽度时遇到了问题,我的代码适用于 iPhone 6s,但不适用于 iPhone 4s 和 iPhone 5s。
这是我的代码:
let originalText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique ipsum non pretium mollis. Curabitur tristique asfhaksjf sfjhksafhdaf ahsdifhsadfh asdfhsahfoas sdofhasdhfasdf"
label.text = originalText
let labelWidth = label.frame.size.width * CGFloat(label.numberOfLines)
let str = label.text! as NSString
let words = str.componentsSeparatedByString(" ")
var newStr = "" as NSString
for word in words {
let statement = "\(newStr) \(word) ... Read more" as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName: label.font])
let readMoreStatement = " ... Read more" as NSString
let sizeReadMore = readMoreStatement.sizeWithAttributes([NSFontAttributeName : label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
label.text = newStr as String
} else {
newStr = newStr.stringByAppendingString("... Read More")
label.text = newStr as String
break
}
}
这是 4s 上的结果:
这是 6s 的结果:
有什么建议我可以如何解决这个问题吗?
最佳答案
您需要首先自动约束您的标签并使用以下代码
let originalText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique ipsum non pretium mollis. Curabitur tristique asfhaksjf sfjhksafhdaf ahsdifhsadfh asdfhsahfoas sdofhasdhfasdf"
label.text = originalText
print((label.text?.characters.count)!)
if (label.text?.characters.count)! < 100 {
label.text = originalText
label.center = view.center
label.textAlignment = .justified
label.adjustsFontSizeToFitWidth = true // If you want a dynamic font size
label.sizeToFit()
print(label.text!) // If character count less then 100 approximately 3 lines
} else {
label.text = "...Read more"
label.textAlignment = .center
print(label.text!) //If character count more then 100 exceeds 3 lines
// You can setup a UIButton here for your "...Read more" action
}
希望这对您有帮助......
关于ios - 在UILabel IOS的特定部分添加文本 "...Read more",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39537496/