如何改变UITextView链接的颜色?

阅读 6.5k
1 个回答

stonemonk
在iOS 7里你可以设置UITextView的 tintColor。它会影响链接的颜色,以及光标和选择文本的颜色。


Leandro Alves
我用UIWebView 代替UITextView,启用"auto-detect links"。只要给TAG创建一个固定CSS就可以改变连接的颜色。
我用的是这个:

NSString * htmlString = [NSString stringWithFormat:@"<html><head><script> document.ontouchmove = function(event) { if (document.body.scrollHeight == document.body.clientHeight) event.preventDefault(); } </script><style type='text/css'>* { margin:0; padding:0; } p { color:black; font-family:Helvetica; font-size:14px; } a { color:#63B604; text-decoration:none; }</style></head><body><p>%@</p></body></html>", [update objectForKey:@"text"]];
webText.delegate = self;
[webText loadHTMLString:htmlString baseURL:nil];

Alexander
我发现一个不用Webview的方式。但是得使用私有API,并且可能被Appstore拒绝。
注:我的APP 虽然用了私有API,但是通过了Appstore的批准。
先用下面的函数在UITextView上声明一个类 :

- (id)contentAsHTMLString;
- (void)setContentToHTMLString:(id)arg1;

这是在做以下几点:

- (id)contentAsHTMLString;
{
    return [super contentAsHTMLString];
}

- (void)setContentToHTMLString:(id)arg1;
{
    [super setContentToHTMLString:arg1];
}

现在为丰富多彩的链接写一个函数:

- (void) colorfillLinks;
{
    NSString *contentString = [self.textViewCustomText contentAsHTMLString];
    contentString = [contentString stringByReplacingOccurrencesOfString:@"x-apple-data-detectors=\"true\""
                                         withString:@"x-apple-data-detectors=\"true\" style=\"color:white;\""];
    [self.textViewCustomText setContentToHTMLString:contentString];
}

这能给所有类型的连接设置特定颜色的样式属性。
使用div可以使UITextViews像Webiview那样显示,所以你甚至可以给每个类型的链接分别设置不同的颜色。

<div><a href="http://www.apple.com" x-apple-data-detectors="true" style="color:white;" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">http://www.apple.com</a></div>

x-apple-data-detectors-type="link"是正确链接类型的指示器。
注:这个在iOS 7 里就不起作用了。在iOS 7 里,设置就可以轻松改变链接的颜色。不要调用

- (id)contentAsHTMLString;

你会遇到一个异常,如果想支持iOS 7,试试下面的:

- (void) colorfillLinks;
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    self.tintColor = [UIColor colorWithRed:79.0/255.0
                                     green:168.0/255.0
                                      blue:224.0/255.0
                                     alpha:1.0];
} else if(![self isFirstResponder ]) {
    NSString *contentString = [self contentAsHTMLString];
    contentString = [contentString stringByReplacingOccurrencesOfString:@"x-apple-data-detectors=\"true\""
                                                             withString:@"x-apple-data-detectors=\"true\" style=\"color:#DDDDDE;\""];
    [self setContentToHTMLString:contentString];

}
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进