How do I make an attributed string using Swift?

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

    Swift 4.2

    extension UILabel {
    
        func boldSubstring(_ substr: String) {
            guard substr.isEmpty == false,
                let text = attributedText,
                let range = text.string.range(of: substr, options: .caseInsensitive) else {
                    return
            }
            let attr = NSMutableAttributedString(attributedString: text)
            let start = text.string.distance(from: text.string.startIndex, to: range.lowerBound)
            let length = text.string.distance(from: range.lowerBound, to: range.upperBound)
            attr.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: self.font.pointSize)],
                               range: NSMakeRange(start, length))
            attributedText = attr
        }
    }
    

提交回复
热议问题