我希望OHAttributedLabel中的一些单词是链接,但我希望它们是蓝色以外的 colored颜色 ,我不希望下划线.

这给了我一个带下划线的蓝色链接:

 -(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{

    NSMutableAttributedString* mutableAttributedText = [self.label.attributedText mutableCopy];   

    [mutableAttributedText beginEditing];
    [mutableAttributedText addAttribute:kOHLinkAttributeName
                   value:[NSURL URLWithString:@"http://www.somewhere.net"]
                   range:range];

    [mutableAttributedText addAttribute:(id)kCTForegroundColorAttributeName
                   value:color
                   range:range];

    [mutableAttributedText addAttribute:(id)kCTUnderlineStyleAttributeName
                   value:[NSNumber numberWithInt:kCTUnderlineStyleNone]
                   range:range];
    [mutableAttributedText endEditing];


    self.label.attributedText = mutableAttributedText;

}

因为我使用的是OHAttributedLabel,所以我也try 了使用它的NSAttributedString+Attributes.h个类别中的方法,但这些方法也会返回蓝色下划线的链接:

-(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{

NSMutableAttributedString* mutableAttributedText = [self.label.attributedText mutableCopy];

[mutableAttributedText setLink:[NSURL URLWithString:@"http://www.somewhere.net"] range:range];
[mutableAttributedText setTextColor:color range:range];
[mutableAttributedText setTextUnderlineStyle:kCTUnderlineStyleNone range:range];

self.label.attributedText = mutableAttributedText;
}

如果我在每个版本中注释掉设置链接的行,文本就会根据我传入的内容上色——这很有效.看起来设置链接覆盖了这一点,并将其恢复为蓝色.

不幸的是,我找到的apple docs页面显示了如何将链接文本设置为蓝色并在其下方加下划线,这正是我不需要的:

推荐答案

所以我最终使用了TTTAttributedLabel:

-(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{
    NSMutableAttributedString* newTextWithLinks = [self.label.attributedText mutableCopy];
    NSURL *url = [NSURL URLWithString:@"http://www.reddit.com"];
    self.label.linkAttributes = @{NSForegroundColorAttributeName: color, 
                                   NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)};
    [self.label addLinkToURL:url withRange:range];
}

我发现OHAttributedLabel个确实有方法设置链接,并为这些链接声明 colored颜色 和下划线样式.但是,我希望链接基于参数而具有不同的 colored颜色 .TTTAttributedLabel允许您为创建的每个链接设置linkAttributes属性.

Objective-c相关问答推荐

iOS:警告try 呈现其视图不在窗口层次 struct 中的 ViewController

在哪里可以找到 iPad 示例代码

向 iOS 应用程序添加自定义字体以查找其真实姓名

xcode 未知类型名称

判断一个 NSDate 是否大于另一个

实现 -hash / -isEqual: / -isEqualTo...: 用于 Objective-C 集合

如何判断特定的 ViewController 视图当前是否可见?

UIViewController 的 prefersStatusBarHidden 不起作用

为什么 NSOrderedSet 不继承自 NSSet?

如何在Objective C(NSRegularExpression)中编写正则表达式?

反转 NSString 文本

如何在 ios 8 的 alertview 中添加文本输入?

获取包含在 NSString 中的文件的扩展名

Objective-C 中的非正式协议?

UITableViewCell 右侧有图像?

使用 NSLog 打印 NSData

-fembed-bitcode 在 6.0 之前的 iOS 版本上不受支持

在 UITableView 中更改复选标记的 colored颜色

从带有参数的方法名称创建 Select 器

如何在不管理 UDID 和重新编译的情况下无线分发 ios 应用程序