5

I am trying to make a UITextView to have two links in it as text, but with different colors. I am not sure if it's possible at all.

I have set the UITextView to detect links, not to be editable, but only selectable.

What I did so far is the following:

NSMutableAttributedString *termsAndConditionsTitle = [[NSMutableAttributedString alloc] initWithString:@"I have read the " attributes:@{NSLinkAttributeName: @"https://apple.com", NSForegroundColorAttributeName: [UIColor greenColor]}];
NSMutableAttributedString *someString2 = [[NSMutableAttributedString alloc] initWithString:@"terms and conditions" attributes:@{NSLinkAttributeName: @"https://microsoft.com", NSForegroundColorAttributeName: [UIColor redColor]}];
[termsAndConditionsTitle appendAttributedString:someString2];
[self.termsAndConditionsView setAttributedText:termsAndConditionsTitle];

But in the end the links just have the tint color of the UITextView. Is it possible to make the two link have different colors? Thanks in advance!

P.S. I don't want to use libraries/frameworks if possible.

scourGINHO
  • 699
  • 2
  • 12
  • 31

2 Answers2

10

Yes it is possible, the problem is that the TextView has some predefined attributes for the links.

To fix it you just have to remove them in this way:

yourTextView.linkTextAttributes = [:]

With this line of code if the textview detects a link it won't apply any special attribute to it. So it will work as usual but without changing the color of the links. If you want to change the colors, you'll have to do it manually when you are adding the attributes.

Pablo Sanchez Gomez
  • 1,438
  • 16
  • 28
-1

You'll need to assign your text view's linkTextAttributes - basically you just tell your text view to identify links and stylize them however you specify:

Objective-C

textView.linkTextAttributes = @{
    NSForegroundColorAttributeName:[UIColor someColor],
    NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)
};

You should also be able to assign the tintColor (since UITextView's inherit the same behavior as UIView's and will use this color for links). But if that isn't working for whatever reason in your case, assigning the link attributes will be the solution.


If your intention was to have two different colors for each link, then you will have to manually assign the attributes of each link based on the range at which each link occurs in your string.

Community
  • 1
  • 1
Will Von Ullrich
  • 2,129
  • 2
  • 15
  • 42