Make part of a UILabel bold in Swift

后端 未结 9 1981
面向向阳花
面向向阳花 2020-12-02 12:50

I have a UILabel I\'ve made programmatically as:

var label = UILabel()

I\'ve then declared some styling for the label, includi

9条回答
  •  醉酒成梦
    2020-12-02 13:37

    Swift 4.0 solution

    let font = UIFont.systemFont(ofSize: 14)
    
    func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)
    
        guard let regex  = try? NSRegularExpression(pattern: searchString.lowercased(), options: []) else {
            return attributedString
        }
    
        let range: NSRange = NSMakeRange(0, resultString.count)
    
        regex.enumerateMatches(in: resultString.lowercased(), options: [], range: range) { (textCheckingResult, matchingFlags, stop) in
            guard let subRange = textCheckingResult?.range else {
                return
            }
    
            attributedString.addAttributes([NSAttributedString.Key.font : font], range: subRange)
        }
    
        return attributedString
    }
    

提交回复
热议问题