具有不同字体大小和颜色的 UILabel 文本
UILabel text with different font size and color
如何使用 Swift 在 UILabel 中设置不同的字体大小和颜色?
我需要用与字符串其余部分不同的颜色和大小为字符串的第一个字符着色。
假设您想要像这样的较小的灰色货币符号:
只需使用一个 NSMutableAttributedString
对象:
let amountText = NSMutableAttributedString.init(string: "€ 60,00")
// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12),
NSForegroundColorAttributeName: UIColor.grayColor()],
range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times
// set the attributed string to the UILabel object
myUILabel.attributedText = amountText
Swift 5.3:
let amountText = NSMutableAttributedString.init(string: "€ 60,00")
// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray],
range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times
// set the attributed string to the UILabel object
// set the attributed string to the UILabel object
myUILabel.attributedText = amountText
如何使用 Swift 在 UILabel 中设置不同的字体大小和颜色?
我需要用与字符串其余部分不同的颜色和大小为字符串的第一个字符着色。
假设您想要像这样的较小的灰色货币符号:
只需使用一个 NSMutableAttributedString
对象:
let amountText = NSMutableAttributedString.init(string: "€ 60,00")
// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12),
NSForegroundColorAttributeName: UIColor.grayColor()],
range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times
// set the attributed string to the UILabel object
myUILabel.attributedText = amountText
Swift 5.3:
let amountText = NSMutableAttributedString.init(string: "€ 60,00")
// set the custom font and color for the 0,1 range in string
amountText.setAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray],
range: NSMakeRange(0, 1))
// if you want, you can add more attributes for different ranges calling .setAttributes many times
// set the attributed string to the UILabel object
// set the attributed string to the UILabel object
myUILabel.attributedText = amountText