How do I make an attributed string using Swift?

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

    The best way to approach Attributed Strings on iOS is by using the built-in Attributed Text editor in the interface builder and avoid uneccessary hardcoding NSAtrributedStringKeys in your source files.

    You can later dynamically replace placehoderls at runtime by using this extension:

    extension NSAttributedString {
        func replacing(placeholder:String, with valueString:String) -> NSAttributedString {
    
            if let range = self.string.range(of:placeholder) {
                let nsRange = NSRange(range,in:valueString)
                let mutableText = NSMutableAttributedString(attributedString: self)
                mutableText.replaceCharacters(in: nsRange, with: valueString)
                return mutableText as NSAttributedString
            }
            return self
        }
    }
    

    Add a storyboard label with attributed text looking like this.

    Then you simply update the value each time you need like this:

    label.attributedText = initalAttributedString.replacing(placeholder: "", with: newValue)
    

    Make sure to save into initalAttributedString the original value.

    You can better understand this approach by reading this article: https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e

提交回复
热议问题