Change the color of a link in an NSMutableAttributedString

Posted feng9exe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Change the color of a link in an NSMutableAttributedString相关的知识,希望对你有一定的参考价值。

Swift

Updated for Swift 3

Use with a textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.green]

And in context:

let attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")

let linkRange = (attributedString.string as NSString).range(of: "@marcelofabri_")

attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: linkRange)

let linkAttributes: [String : Any] = [

    NSForegroundColorAttributeName: UIColor.green,

    NSUnderlineColorAttributeName: UIColor.lightGray,

    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]

 

// textView is a UITextView

textView.linkTextAttributes = linkAttributes

textView.attributedText = attributedString

textView.delegate = self

Swift 4:

let linkAttributes: [String : Any] = [

    NSAttributedStringKey.foregroundColor.rawValue: UIColor.green,

    NSAttributedStringKey.underlineColor.rawValue: UIColor.lightGray,

    NSAttributedStringKey.underlineStyle.rawValue: NSUnderlineStyle.styleSingle.rawValue]

Objective-C

Use with a 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;

 https://stackoverflow.com/questions/28361072/change-the-color-of-a-link-in-an-nsmutableattributedstring

以上是关于Change the color of a link in an NSMutableAttributedString的主要内容,如果未能解决你的问题,请参考以下文章

WPF Tips: Specify background color of the selected item in listbox

change the edition of java on ubuntu.

pandas使用loc函数更新修改dataframe指定数据行的内容(update or change the content of specific row of dataframe)

pandas改变dataframe索引数据列的数据类型(change the index column data type of pandas dataframe)

WPF DataGrid根据内容设置行颜色

python使用matplotlib可视化线图(line plot)自定义可视化图像X轴和Y轴轴标签的色彩(change color of axis in matplotlib)