UITextView linkTextAttributes font attribute not applied to NSAttributedString

后端 未结 8 642
暖寄归人
暖寄归人 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:05

    Since attributed strings are generally a pain, I find it is better to avoid the range APIs, and to keep things as immutable as possible. Set the attributes when you create the attributed string rather than going back and trying to set a range. This will also help with localization because figuring out ranges for different languages is quite tricky (the sample below does not show localization to keep things illustrative). It makes things cleaner and easier to follow. When all strings are constructed, assemble the whole thing from the pieces.

    // build string
    let intro = NSAttributedString(string: "I agree that I have read and understood the ")
    let terms = NSAttributedString(string: "Terms and Conditions ", attributes: [.link: "https://apple.com" as Any])
    let middle = NSAttributedString(string: "and ")
    let privacy = NSAttributedString(string: "Privacy Policy. ", attributes: [.link: "https://example.com" as Any])
    let ending = NSAttributedString(string: "This application may send me SMS messages.")
    let attrStr = NSMutableAttributedString()
    attrStr.append(intro)
    attrStr.append(terms)
    attrStr.append(middle)
    attrStr.append(privacy)
    attrStr.append(ending)
    
    // set the link color
    let linkAttributes: [NSAttributedString.Key: AnyObject] = [.foregroundColor: UIColor(named: "Secondary")!]
    textView.linkTextAttributes = linkAttributes
    textView.attributedText = attrStr
    

提交回复
热议问题