【问题标题】:UILabel text with different font size and color [duplicate]具有不同字体大小和颜色的UILabel文本[重复]
【发布时间】:2016-04-21 04:45:41
【问题描述】:

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

我需要用不同于字符串其余部分的颜色和大小为字符串的第一个字符着色。

【问题讨论】:

    标签: ios swift uilabel


    【解决方案1】:

    假设你想要一个像这样的小而灰色的货币符号:

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

    【讨论】:

    • 这只是一个Self-answer
    • 你好@lifeisfoo - 这不起作用
    • 嗨@ParthDhorda,这段代码非常适合这种情况,其他开发人员发现它很有用。可能你的用例有点不同,你需要问一个具体的问题。
    • 嗨@lifeisfoo 那么唯一的改变是我在tableview中使用它,不仅是你的答案,而且stackover流程中的任何答案都不适合我
    • 这进一步证明您的问题需要专门针对 SO 提出问题 :)
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2020-09-06
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多