Bold & Non-Bold Text In A Single UILabel?

后端 未结 14 2204
别那么骄傲
别那么骄傲 2020-11-22 08:51

How would it be possible to include both bold and non-bold text in a uiLabel?

I\'d rather not use a UIWebView.. I\'ve also read this may be possible using NSAttribut

14条回答
  •  灰色年华
    2020-11-22 09:25

    I've adopted Crazy Yoghurt's answer to swift's extensions.

    extension UILabel {
    
        func boldRange(_ range: Range) {
            if let text = self.attributedText {
                let attr = NSMutableAttributedString(attributedString: text)
                let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
                let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
                attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
                self.attributedText = attr
            }
        }
    
        func boldSubstring(_ substr: String) {
            if let text = self.attributedText {
                var range = text.string.range(of: substr)
                let attr = NSMutableAttributedString(attributedString: text)
                while range != nil {
                    let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
                    let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
                    var nsRange = NSMakeRange(start, length)
                    let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
                    if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                        break
                    }
                    range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..

    May be there is not good conversion between Range and NSRange, but I didn't found something better.

提交回复
热议问题