How do I make an attributed string using Swift?

前端 未结 28 2411
耶瑟儿~
耶瑟儿~ 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:32

    Swift 2.0

    Here is a sample:

    let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
    newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
    sampleLabel.attributedText = newsString.copy() as? NSAttributedString
    

    Swift 5.x

    let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
    newsString.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue], range: NSMakeRange(4, 4))
    sampleLabel.attributedText = newsString.copy() as? NSAttributedString
    

    OR

    let stringAttributes = [
        NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 17.0)!,
        NSUnderlineStyleAttributeName : 1,
        NSForegroundColorAttributeName : UIColor.orangeColor(),
        NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
        NSStrokeWidthAttributeName : 2.0]
    let atrributedString = NSAttributedString(string: "Sample String: Attributed", attributes: stringAttributes)
    sampleLabel.attributedText = atrributedString
    

提交回复
热议问题