Search code examples
iosiphonensattributedstringnsmutableattributedstring

Change the color of a link in an NSMutableAttributedString


I have the following code but my links are always blue. How do I cange the color of them?

[_string addAttribute:NSLinkAttributeName value:tag range:NSMakeRange(position, length)];
[_string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:(12.0)] range:NSMakeRange(position, length)];
[_string addAttribute:NSStrokeColorAttributeName value:[UIColor greenColor] range:NSMakeRange(position, length)];

_string is a NSMutableAttributedString and the position and length work fine.


Solution

  • Swift

    Updated for Swift 4.2

    Use linkTextAttributes with a UITextView

    textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
    

    And in context:

    let attributedString = NSMutableAttributedString(string: "The site is www.google.com.")
    let linkRange = (attributedString.string as NSString).range(of: "www.google.com")
    attributedString.addAttribute(NSAttributedString.Key.link, value: "https://www.google.com", range: linkRange)
    let linkAttributes: [NSAttributedString.Key : Any] = [
        NSAttributedString.Key.foregroundColor: UIColor.green,
        NSAttributedString.Key.underlineColor: UIColor.lightGray,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
    ]
    
    // textView is a UITextView
    textView.linkTextAttributes = linkAttributes
    textView.attributedText = attributedString
    

    Objective-C

    Use linkTextAttributes with a UITextView

    textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor greenColor]};
    

    Source: this answer

    And from this post:

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"username://marcelofabri_"
                             range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];
    
    
    NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
                                     NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                     NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    
    // assume that textView is a UITextView previously created (either by code or Interface Builder)
    textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
    textView.attributedText = attributedString;
    textView.delegate = self;