首页 > 其他 > 详细

Change the color of a link in an NSMutableAttributedString

时间:2018-08-01 17:44:18      阅读:146      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/feng9exe/p/9402372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!