UITextView linkTextAttributes font attribute not applied to NSAttributedString

后端 未结 8 784
暖寄归人
暖寄归人 2021-02-01 20:18

I have an NSAttributedString generated from HTML which includes some links. The attributed string is shown in a UITextView. I wish to apply a different font style f

8条回答
  •  甜味超标
    2021-02-01 21:04

    Swift 5 version of Ryan Heitner's awesome answer:

    guard let attributedString = textView.attributedText else { return }
    guard let linkFont = UIFont(name: "HelveticaNeue-Bold", size: 20.0) else { return }
    
    let newString = NSMutableAttributedString(attributedString: attributedString)
    let types: NSTextCheckingResult.CheckingType = [.link, .phoneNumber]
    
    guard let linkDetector = try? NSDataDetector(types: types.rawValue) else { return }
    let range = NSRange(location: 0, length: attributedString.length)
    
    linkDetector.enumerateMatches(in: attributedString.string, options: [], range: range, using: { (match: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop) in
        if let matchRange = match?.range {
            newString.removeAttribute(NSAttributedString.Key.font, range: matchRange)
            newString.addAttribute(NSAttributedString.Key.font, value: linkFont, range: matchRange)
        }
    })
    
    textView.attributedText = newString
    

提交回复
热议问题