21

我觉得我错过了一些简单的东西,但我似乎无法找到如何做到这一点:

我将属性设置为这样的链接:

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

这可行,但链接是蓝色的,我似乎无法更改颜色。这会将除链接之外的所有内容设置为白色:

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

是否有另一个我似乎找不到特定于链接的颜色属性名称?

4

8 回答 8

65
  1. 用一个UITextView
  2. UITextView像这样设置linkTextAttributes

    textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    
于 2014-09-04T00:30:41.400 回答
3

我实际上最终使用了TTTAttributedLabel作为我的标签,然后能够执行以下完美工作:

NSDictionary *linkAttributes = @{(id)kCTForegroundColorAttributeName: [UIColor whiteColor],
                                 (id)kCTUnderlineStyleAttributeName: [NSNumber numberWithInt:kCTUnderlineStyleSingle]
                                 };
self.lblDescription.linkAttributes = linkAttributes;    
于 2014-09-04T04:47:57.650 回答
3

txtLabel.linkAttributes = @{};

这是正确的,在设置任何其他属性之前调用此行

于 2016-12-07T12:58:38.357 回答
2

快速(供他人参考):

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

myTextView.linkTextAttributes = linkAttributes as [NSObject : AnyObject]
于 2015-04-28T20:48:36.873 回答
2

解释:

这非常简单,支持链接检测的文本组件有一个名为linkTextAttributes.

此属性存储链接的样式,因为组件可以在检测到新链接时应用它。

总而言之,将应用您的样式,然后应用存储在此属性中的样式(按此顺序),成功覆盖您想要的样式

解决方案:

将此属性设置为空 ( linkTextAttributes = [:]) 并完全控制您的链接样式。


提示:这可用于在您的设备上创建行为类似于按钮的可触摸元素UITextView。创建一个非常好的效果

于 2017-06-27T20:35:40.537 回答
2

对于斯威夫特 3

var aURL = "Http:// Your URL"
var description = "Click Me:"
let attributedString = NSMutableAttributedString(string: description + aURL)

/// Deal with link color
let foundURLRange = attributedString.mutableString.range(of: aURL)
attributedString.addAttribute(NSLinkAttributeName, value: aURL, range: foundURLRange)
textview.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.yellow]

/// Deal with description color
let foundDescriptionRange = attributedString.mutableString.range(of: description)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: foundDescriptionRange)

textview.attributedText = attributedString

在此处输入图像描述

于 2017-09-22T02:33:15.377 回答
1

这对我有用:

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];
}
于 2016-09-09T09:52:27.757 回答
-1

如果您使用 TTTAttributedLabel,Oren 的答案是有效的。但是您需要注意链接属性在注释中的警告。

/**包含 要应用于检测到或手动添加到标签文本的链接
的默认属性的字典。NSAttributedString默认链接样式为蓝色并带有下划线。

@warning 您必须linkAttributes在为要应用的这些属性设置自动检测或手动添加链接之前指定。
*/

@property (nonatomic, strong) NSDictionary *linkAttributes;

于 2017-01-06T17:52:50.907 回答