How do I make an attributed string using Swift?

前端 未结 28 1731
耶瑟儿~
耶瑟儿~ 2020-11-22 10:11

I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The \"g\" symbol for grams needs to be attached to my UILabel that I am usin

28条回答
  •  粉色の甜心
    2020-11-22 10:58

    Swift uses the same NSMutableAttributedString that Obj-C does. You instantiate it by passing in the calculated value as a string:

    var attributedString = NSMutableAttributedString(string:"\(calculatedCoffee)")
    

    Now create the attributed g string (heh). Note: UIFont.systemFontOfSize(_) is now a failable initializer, so it has to be unwrapped before you can use it:

    var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(19.0)!]
    var gString = NSMutableAttributedString(string:"g", attributes:attrs)
    

    And then append it:

    attributedString.appendAttributedString(gString)
    

    You can then set the UILabel to display the NSAttributedString like this:

    myLabel.attributedText = attributedString
    

提交回复
热议问题