UITextView中有两个不同颜色的超链接?

5

我正在尝试将UITextView设置为包含两个链接的文本,但是颜色不同。 我不确定这是否可能。

我已将UITextView设置为检测链接,而不可编辑,仅可选择。

我到目前为止所做的是:

NSMutableAttributedString *termsAndConditionsTitle = [[NSMutableAttributedString alloc] initWithString:@"I have read the " attributes:@{NSLinkAttributeName: @"https://apple.com", NSForegroundColorAttributeName: [UIColor greenColor]}];
NSMutableAttributedString *someString2 = [[NSMutableAttributedString alloc] initWithString:@"terms and conditions" attributes:@{NSLinkAttributeName: @"https://microsoft.com", NSForegroundColorAttributeName: [UIColor redColor]}];
[termsAndConditionsTitle appendAttributedString:someString2];
[self.termsAndConditionsView setAttributedText:termsAndConditionsTitle];

但最终,链接只有UITextView的色调颜色。是否可以使这两个链接具有不同的颜色?提前感谢!

附言:如有可能,我不想使用库/框架。

1
https://dev59.com/BHM_5IYBdhLWcg3wgja2#46551112 - Tamás Sengel
2个回答

10

是的,这是可能的,问题在于TextView有一些预定义的链接属性。

要解决这个问题,您只需要以这种方式删除它们:

yourTextView.linkTextAttributes = [:]

使用此代码行,如果文本视图检测到链接,它将不会应用任何特殊属性。因此,它将像往常一样工作,但不会更改链接的颜色。如果您想更改颜色,则必须在添加属性时手动执行。


伙计,你刚刚帮我省下了几个小时的头疼时间。感谢你的回复。 - ibyte

-1
你需要为你的文本视图分配linkTextAttributes - 基本上,你只需告诉你的文本视图识别链接并按照你指定的样式进行排版:

Objective-C

textView.linkTextAttributes = @{
    NSForegroundColorAttributeName:[UIColor someColor],
    NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)
};

你还应该能够分配tintColor(因为UITextView继承了与UIView相同的行为,并将使用此颜色来显示链接)。但是如果在您的情况下由于某种原因无法正常工作,则分配链接属性将是解决方案。


如果您的意图是为每个链接分配两种不同的颜色,那么您将需要根据字符串中每个链接出现的范围手动分配每个链接的属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接