UILabel文本的不同字体大小和颜色

17

如何使用Swift设置UILabel中不同的字体大小和颜色?

我需要将字符串的第一个字符与其余部分使用不同的颜色和大小。

1个回答

53

假设您想要一个像这样更小和灰色的货币符号:

enter image description here

只需使用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

13
这只是一个自问自答 - lifeisfoo
你好 @lifeisfoo - 这个不起作用。 - Parth Dhorda
嗨@ParthDhorda,这段代码在这种情况下运行得很好,其他开发人员也发现它很有用。可能你的用例有点不同,需要针对它提出具体问题。 - lifeisfoo
嗨@lifeisfoo,唯一的变化是我正在表格视图中使用它,不仅仅是你的答案,而且来自Stack Overflow的任何答案都对我没有用。 - Parth Dhorda
这进一步证明了你的问题需要在SO上提出一个专门的问题 :) - lifeisfoo
我认为这不需要一个专门的问题,因为归属文本在标签和UITableView内部的工作方式是相同的。 - Parth Dhorda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接