Search code examples
swiftxcodetextviewswift4nsattributedstring

UITextView : the foregroundColor of link attributes dont change (NSAttributedStringKey)


I have a problem with NSAttributedStringKey and UITextView

In fact, I am trying to do this :

enter image description here

Here is the code that should theoretically work

class ViewController: UIViewController,UITextViewDelegate {
 @IBOutlet weak var txtView: UITextView!
 override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self;
    let linkAttributes : [NSAttributedStringKey : Any] = [
            .link: URL(string: "https://exemple.com")!,
            .font:UIFont.boldSystemFont(ofSize: 18),
            .foregroundColor: UIColor.blue] ;
    let attributedString = NSMutableAttributedString(string: "Just 
     click here to do stuff...")
    attributedString.setAttributes(linkAttributes, range: 
    NSMakeRange(5, 10))
     txtView.attributedText = attributedString;
}}

but this code displays this

enter image description here

so I tried to solve the problem by adding two extra lines of code :

 let linkAttributes : [NSAttributedStringKey : Any] = [
            .link: URL(string: "https://exemple.com")!,
            .font:UIFont.boldSystemFont(ofSize: 18),
            .foregroundColor: UIColor.blue,
            .strokeColor : UIColor.black,//new line
            .strokeWidth : -1,//new line
           ] ;

Unfortunately, the display wasn't what I wanted.

enter image description here

Someone to help me on this problem, I searched the internet but found nothing.

Thanks in advance

INFO : the first image I took of this publication :Link in UITextView not working in Swift 4


Solution

  • seems that ".link" uses the tintColor of UITextView. Try setting the tintColor...