是否可以为 UILabel 中的一个字符设置不同的颜色?
Is it possible to set a different colour for one character in a UILabel?
我一直在使用 Xcode 进行一个小项目。它使用了很多标签、文本字段等。我已经完成了大部分布局、约束以及表单、标题等。之后,客户宣布对于所有必填字段,应该有一个红色星号在标签旁边。
说我懒惰,但我宁愿不回到我的所有表格,添加很多带有星号的标签,re-do 我的 auto-layout 以适应新的标签。
那么,有没有一种方法可以更改 UILabel 中特定字符(在本例中为星号)的颜色,而其余文本保持黑色?
您可以使用 NSMutableAttributedString
。
您可以使用不同的颜色、字体、大小、...
设置字符串的特定范围
例如:
var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2
attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
// here you change the character to red color
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
label.attributedText = attributedString
参考:
你可以改变很多String的属性。
来自苹果的参考:https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html
let text = "Sample text *"
let range = (text as NSString).rangeOfString("*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
//Apply to the label
myLabel.attributedText = attributedString;
UILabel
有一个 .attributedText
属性 类型 NSAttributedString
.
Declaration
@NSCopying var attributedText: NSAttributedString?
你让你的 asterix *
有一个单一的 .redColor()
属性 (NSForegroundColorAttributeName
),而新标签的其余部分只使用与以前相同的文本,但也包含在一个 NSAttributedTextString
。
下面的示例使用函数将现有标签重复更新为带有红色前缀 *
的属性字符串:
class ViewController: UIViewController {
@IBOutlet weak var myFirstLabel: UILabel!
@IBOutlet weak var mySecondLabel: UILabel!
let myPrefixCharacter = "*"
let myPrefixColor = UIColor.redColor()
// ...
override func viewDidLoad() {
super.viewDidLoad()
// ...
/* update labels to attributed strings */
updateLabelToAttributedString(myFirstLabel)
updateLabelToAttributedString(mySecondLabel)
// ...
}
func updateLabelToAttributedString(label: UILabel) {
/* original label text as NSAttributedString, prefixed with " " */
let attr = [ NSForegroundColorAttributeName: myPrefixColor ]
let myNewLabelText = NSMutableAttributedString(string: myPrefixCharacter, attributes: attr)
let myOrigLabelText = NSAttributedString(string: " " + (label.text ?? ""))
/* set new label text as attributed string */
myNewLabelText.appendAttributedString(myOrigLabelText)
label.attributedText = myNewLabelText
}
// ...
}
我知道这是一个旧的 post,但我想分享我的方法(基于 dfri 的回答)我只是为了方便而将其作为一个函数。
func lastCharOnColor(label: UILabel, color: UIColor, length: Int) {
//First we get the text.
let string = label.text
//Get number of characters on string and based on that get last character index.
let characterCounter = string?.characters.count
let lastCharacterIndex = characterCounter!-1
//Set Range
let range = NSRange(location: lastCharacterIndex, length: length)
let attributedString = NSMutableAttributedString(string: string!, attributes: nil)
//Set label
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
label.attributedText = attributedString
}
我使用此函数将标签的最后一个字符设置为特定颜色,如下所示:
lastCharOnColor(label: self.labelname, color: UIColor.red, length: 1)
希望这对任何人都有帮助。
Swift 4
(注意:在 swift 4 中更改了属性字符串键的表示法)
这是 NSMutableAttributedString
的扩展,即 string/text 上的 add/set 颜色。
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)
func updateAttributedStringWithCharacter(title : String, uilabel: UILabel) {
let text = title + "*"
let range = (text as NSString).range(of: "*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
uilabel.attributedText = attributedString }
这是一个扩展,通过附加一个红色 *
来简单地制作强制性标签
Swift 5
extension UILabel {
func makeTextMandatory() {
let text = self.text ?? "" + " *"
let range = (text as NSString).range(of: " *")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
self.attributedText = attributedString
}
}
用法:
dobLabel.makeTextMandatory()
我一直在使用 Xcode 进行一个小项目。它使用了很多标签、文本字段等。我已经完成了大部分布局、约束以及表单、标题等。之后,客户宣布对于所有必填字段,应该有一个红色星号在标签旁边。
说我懒惰,但我宁愿不回到我的所有表格,添加很多带有星号的标签,re-do 我的 auto-layout 以适应新的标签。
那么,有没有一种方法可以更改 UILabel 中特定字符(在本例中为星号)的颜色,而其余文本保持黑色?
您可以使用 NSMutableAttributedString
。
您可以使用不同的颜色、字体、大小、...
例如:
var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2
attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
// here you change the character to red color
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
label.attributedText = attributedString
参考:
你可以改变很多String的属性。 来自苹果的参考:https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html
let text = "Sample text *"
let range = (text as NSString).rangeOfString("*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
//Apply to the label
myLabel.attributedText = attributedString;
UILabel
有一个 .attributedText
属性 类型 NSAttributedString
.
Declaration
@NSCopying var attributedText: NSAttributedString?
你让你的 asterix *
有一个单一的 .redColor()
属性 (NSForegroundColorAttributeName
),而新标签的其余部分只使用与以前相同的文本,但也包含在一个 NSAttributedTextString
。
下面的示例使用函数将现有标签重复更新为带有红色前缀 *
的属性字符串:
class ViewController: UIViewController {
@IBOutlet weak var myFirstLabel: UILabel!
@IBOutlet weak var mySecondLabel: UILabel!
let myPrefixCharacter = "*"
let myPrefixColor = UIColor.redColor()
// ...
override func viewDidLoad() {
super.viewDidLoad()
// ...
/* update labels to attributed strings */
updateLabelToAttributedString(myFirstLabel)
updateLabelToAttributedString(mySecondLabel)
// ...
}
func updateLabelToAttributedString(label: UILabel) {
/* original label text as NSAttributedString, prefixed with " " */
let attr = [ NSForegroundColorAttributeName: myPrefixColor ]
let myNewLabelText = NSMutableAttributedString(string: myPrefixCharacter, attributes: attr)
let myOrigLabelText = NSAttributedString(string: " " + (label.text ?? ""))
/* set new label text as attributed string */
myNewLabelText.appendAttributedString(myOrigLabelText)
label.attributedText = myNewLabelText
}
// ...
}
我知道这是一个旧的 post,但我想分享我的方法(基于 dfri 的回答)我只是为了方便而将其作为一个函数。
func lastCharOnColor(label: UILabel, color: UIColor, length: Int) {
//First we get the text.
let string = label.text
//Get number of characters on string and based on that get last character index.
let characterCounter = string?.characters.count
let lastCharacterIndex = characterCounter!-1
//Set Range
let range = NSRange(location: lastCharacterIndex, length: length)
let attributedString = NSMutableAttributedString(string: string!, attributes: nil)
//Set label
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
label.attributedText = attributedString
}
我使用此函数将标签的最后一个字符设置为特定颜色,如下所示:
lastCharOnColor(label: self.labelname, color: UIColor.red, length: 1)
希望这对任何人都有帮助。
Swift 4
(注意:在 swift 4 中更改了属性字符串键的表示法)
这是 NSMutableAttributedString
的扩展,即 string/text 上的 add/set 颜色。
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)
func updateAttributedStringWithCharacter(title : String, uilabel: UILabel) {
let text = title + "*"
let range = (text as NSString).range(of: "*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
uilabel.attributedText = attributedString }
这是一个扩展,通过附加一个红色 *
来简单地制作强制性标签Swift 5
extension UILabel {
func makeTextMandatory() {
let text = self.text ?? "" + " *"
let range = (text as NSString).range(of: " *")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
self.attributedText = attributedString
}
}
用法:
dobLabel.makeTextMandatory()