Uilabel带有两个不同颜色的文本
-
08-10-2019 - |
题
我怎么能拥有 UILabel
具有两种不同的字体颜色?我将以两个不同的字符串中的文字进行文字,我想用第一个字符串作为 红色的 第二 绿色. 。两个字符串的长度都是可变的。
解决方案
你不能在 UILabel
s。但是我的建议是,而不是使用多个 UILabel
只是集中精力 NSAttributedString
. 。寻找 UIControllers
抽奖 NSAttributedString
因为 UILabel
, UITextView
不支持 NSAttributedString
.
PS:如果您打算分发ios6或更高版本的应用程序,因为Uilabel现在支持NSATTRIBDERSTRING,则应直接使用Uilabel而不是OHATTRIBETEDLABEL,因为它现在由OS固定支持。
其他提示
尝试 tttattribedlabel. 。这是Uilabel的子类 NSAttributedString
S,这将使在同一字符串中具有多种颜色,字体和样式变得容易。
编辑:或者,如果您不想要第三方依赖性,并且针对iOS 6, UILabel
现在有 attributedText
财产。
Uilabel只能 一 颜色。您要么需要一个更复杂的元素,要么 - 可能更容易 - 只需使用两个单独的标签即可。利用 [yourLabel sizeToFit];
并将它们放置。
Swift 4
(注意:属性字符串键的符号在Swift 4中已更改)
这是一个扩展 NSMutableAttributedString
, ,在字符串/文本上添加/设置颜色。
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
现在,尝试以上扩展 UILabel
并查看结果
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
这是解决方案 Swift 3:
extension NSMutableAttributedString {
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
if range != nil {
self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
}
}
func multicolorTextLabel() {
var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen")
string.setColorForText(textToFind: "red", withColor: UIColor.red)
string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
string.setColorForText(textToFind: "green", withColor: UIColor.green)
labelObject.attributedText = string
}
结果:
在iOS 6中,uilabel具有nsattributedstring属性。所以使用它。