How do I make an attributed string using Swift?

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

    Swifter Swift has a pretty sweet way to do this without any work really. Just provide the pattern that should be matched and what attributes to apply to it. They're great for a lot of things check them out.

    ``` Swift
    let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
    let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
    ``
    

    If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.

    You can do this in one step, just easier to read when separated.

提交回复
热议问题