Reputation: 428
I have a problem with NSAttributedStringKey and UITextView
In fact, I am trying to do this :
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
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.
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
Upvotes: 4
Views: 819
Reputation: 178
seems that ".link" uses the tintColor of UITextView. Try setting the tintColor...
Upvotes: 6
Reputation: 89549
I got your code to work with minimal tweaking:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let basicAttributes : [NSAttributedStringKey : Any] = [
.font: UIFont.systemFont(ofSize: 18),
.foregroundColor: UIColor.black]
let linkAttributes : [NSAttributedStringKey : Any] = [
.link: URL(string: "https://www.stackoverflow.com")!,
.font:UIFont.boldSystemFont(ofSize: 18),
.foregroundColor: UIColor.blue]
let attributedString = NSMutableAttributedString(string: "Just click here to do stuff...", attributes: basicAttributes)
attributedString.addAttributes(linkAttributes, range: NSMakeRange(5, 10))
textView.attributedText = attributedString
}
You probably notice I set the font for the entire string (which is probably not necessary, especially if you already set the UITextView object's font in your XIB or storyboard), but I'm guessing the real solution is to use addAttributes
, which adds the link attributes to the other attributes in the attributed string.
Upvotes: 2