Setting NSLinkAttributeName font color

2019-02-11 14:11发布

I feel like I'm missing something easy but I can't seem to find out how to do this:

I set the attribute to a link like so:

[myAttrString addAttribute:NSLinkAttributeName value:linkURL range:selectedRange];

That works but the link is blue and I can't seem to change the color. This sets everything except the link to white:

[myAttrString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:selectedRange];

Is there another color attribute name that I can't seem to find that is specific to links?

8条回答
闹够了就滚
2楼-- · 2019-02-11 14:18

Explanation:

This is surprisingly easy, text components that supports link detection have a property called linkTextAttributes.

This property stores the style for the link as of the component can apply it when detects a new link.

Summing up, your style will be applied and then the style stored in this property (in this order), successfully overriding your desired style.

Solution:

Set this property to empty ( linkTextAttributes = [:] ) and take total control of you link Styles.


TIP: This can be used to create touchable elements on your UITextView that behaves like a button. Creating a Really nice effect

查看更多
够拽才男人
3楼-- · 2019-02-11 14:19

This works for me:

txtLabel.linkAttributes = @{};

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:expression];

{
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:result.range];

[string addAttribute:NSLinkAttributeName value:@"link" range:result.range];
}
查看更多
萌系小妹纸
4楼-- · 2019-02-11 14:23
  1. Use a UITextView
  2. Set the UITextView's linkTextAttributes like so:

    textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    
查看更多
做个烂人
5楼-- · 2019-02-11 14:24

If you use TTTAttributedLabel, Oren's answer is worked.But you need to pay attention to the linkAttributes's warning in annotation.

/**
A dictionary containing the default NSAttributedString attributes to be applied to links detected or manually added to the label text. The default link style is blue and underlined.

@warning You must specify linkAttributes before setting autodecting or manually-adding links for these attributes to be applied.
*/

@property (nonatomic, strong) NSDictionary *linkAttributes;

查看更多
ら.Afraid
6楼-- · 2019-02-11 14:33

txtLabel.linkAttributes = @{};

This is the right one, call this line before set any other attribute

查看更多
干净又极端
7楼-- · 2019-02-11 14:41

For swift (for reference for others):

// Color the links
var linkAttributes: NSMutableDictionary = NSMutableDictionary()
linkAttributes.setValue(self.appDelegate.variables.color320, forKey: NSForegroundColorAttributeName)

myTextView.linkTextAttributes = linkAttributes as [NSObject : AnyObject]
查看更多
登录 后发表回答