我正在UILabel中进行多色文本处理。它运作良好。但问题是我明白了,我可以在uilabel中显示多行。这意味着numberOfLine函数无法正常工作。
extension NSMutableAttributedString {
func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
let stringValue = "Natural air is most important part of human body. people got too much problem because of it. please everybody try to do best part for it"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "\(item.catName ?? "")", withColor: Colors.green)
postInfoLabel.font = UIFont.systemFont(ofSize: ViewSize.width/33)
postInfoLabel.numberOfLines = 0
postInfoLabel.attributedText = attributedString
用于包装和截断标签文本的技术是根据您的用例将lineBreakMode属性值设置为NSLineBreakByWordWrapping或NSLineBreakByTruncatingTail。当您将UILabel的numberOfLines属性设置为0时,这应该对您有用。
numberOfLines
不是函数,而是指示UILabel
应显示多少行的属性。如果将此值设置为0
,则告诉标签使用所需的多行来显示文本。您可以在numberOfLines documentation中阅读更多详细信息。