How do I make an attributed string using Swift?

前端 未结 28 1717
耶瑟儿~
耶瑟儿~ 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
    
    0 讨论(0)
  • 2020-11-22 10:59

    Swift 5 and above

       let attributedString = NSAttributedString(string:"targetString",
                                       attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                                                   NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])
    
    0 讨论(0)
  • 2020-11-22 10:59

    Swift 4

    let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
    
    let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
    

    You need to remove the raw value in swift 4

    0 讨论(0)
  • 2020-11-22 10:59

    The attributes can be setting directly in swift 3...

        let attributes = NSAttributedString(string: "String", attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 30)!,
             NSForegroundColorAttributeName : UIColor .white,
             NSTextEffectAttributeName : NSTextEffectLetterpressStyle])
    

    Then use the variable in any class with attributes

    0 讨论(0)
提交回复
热议问题