在iOS中,有没有办法在一个标签中使用两种、甚至三种字体 colored颜色 ?
如果以文字"hello,are are you"为例,那么"hello"将是蓝色的,而"hello are you"将是绿色的.
这是可能的吗,这看起来比创建多个标签更容易吗?
在iOS中,有没有办法在一个标签中使用两种、甚至三种字体 colored颜色 ?
如果以文字"hello,are are you"为例,那么"hello"将是蓝色的,而"hello are you"将是绿色的.
这是可能的吗,这看起来比创建多个标签更容易吗?
首先,初始化NSString和NSMutableAttributedString,如下所示.
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
在ViewDidLoad个月内
override func viewDidLoad() {
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
OUTPUT
MULTIPLE COLOR个
在ViewDidLoad中添加下面的行代码,以获得字符串中的多种 colored颜色 .
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))
Multiple color OUTPUT
Swift 4个
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
Swift 5.0个
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))