我可以更改 UITextView 上自动检测到的链接的颜色吗?

发布于 2024-08-02 20:08:19 字数 145 浏览 4 评论 0原文

我有一个 UITextView 可以检测电话号码和链接,但这会覆盖我的 fontColor 并将其更改为 blueColor。有没有办法格式化自动检测到的链接的颜色,或者我应该尝试此功能的手动版本?

I had a UITextView that detects phone numbers and links, but this overrides my fontColor and change it to blueColor. Is there a way to format the color of auto detected links, or should I try a manual version of this function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

江城子 2024-08-09 20:08:19

在 iOS 7 上,您可以设置 UITextViewtintColor。它会影响链接颜色以及光标线和所选文本颜色。

iOS 7 还在 UITextView 中添加了一个名为 linkTextAttributes 的新属性,它似乎可以让您完全控制链接样式。

On iOS 7 you can set the tintColor of the UITextView. It affects the link color as well as the cursor line and the selected text color.

iOS 7 also added a new property to UITextView called linkTextAttributes which would appear to let you fully control the link style.

沉鱼一梦 2024-08-09 20:08:19

您可以使用 UIAppearance 协议对所有文本视图应用更改:

Swift 4.x+:

UITextView.appearance().linkTextAttributes = [ .foregroundColor: UIColor.red ]

Swift 3.x:

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.red ]

Swift 2.x:

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.redColor() ]

Objective-C:

[UITextView appearance].linkTextAttributes = @{ NSForegroundColorAttributeName : UIColor.redColor };

Appearance for UITextView没有记录,但效果很好。

请记住 UIAppearance 注意事项:

当视图进入窗口时,iOS 会应用外观更改,但不会更改窗口中已有视图的外观。要更改窗口中当前视图的外观,请从视图层次结构中删除该视图,然后将其放回去。

换句话说:
init()init(coder:) 方法中调用此代码更改 UI 对象外观,但在 loadView( ),或 viewController 的 viewDidLoad() 不会
如果您想设置整个应用程序的外观,application(_:didFinishLaunchingWithOptions:) 是调用此类代码的好地方。

You can use the UIAppearance protocol to apply changes for all text views:

Swift 4.x+:

UITextView.appearance().linkTextAttributes = [ .foregroundColor: UIColor.red ]

Swift 3.x:

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.red ]

Swift 2.x:

UITextView.appearance().linkTextAttributes = [ NSForegroundColorAttributeName: UIColor.redColor() ]

Objective-C:

[UITextView appearance].linkTextAttributes = @{ NSForegroundColorAttributeName : UIColor.redColor };

Appearance for UITextView is not documented, but works well.

Keep in mind UIAppearance notes:

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

In other words:
Calling this code in init(), or init(coder:) methods will change UI Object appearance, but calling in loadView(), or viewDidLoad() of viewController won't.
If you want to set appearance for whole application, application(_:didFinishLaunchingWithOptions:) is good place for calling such code.

卸妝后依然美 2024-08-09 20:08:19

我没有使用 UITextView,而是使用了 UIWebView 并启用了“自动检测链接”。要更改链接颜色,只需为标签创建常规 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];

Instead of using an UITextView, I used an UIWebView and enabled the "auto-detect links". To change the link color, just created a regular CSS for the tag.

I used something like this:

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];
梅倚清风 2024-08-09 20:08:19

UITextView linkTextAttributes 的问题在于它适用于所有自动检测到的链接。如果您希望不同的链接具有不同的属性怎么办?

事实证明有一个技巧:将链接配置为文本视图属性文本的一部分,并将 linkTextAttributes 设置为空字典。

这是 iOS 11 / Swift 4 中的示例:

// mas is the mutable attributed string we are forming...
// ... and we're going to use as the text view's `attributedText`
mas.append(NSAttributedString(string: "LINK", attributes: [
    NSAttributedStringKey.link : URL(string: "https://www.apple.com")!,
    NSAttributedStringKey.foregroundColor : UIColor.green,
    NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]))
// ...
self.tv.attributedText = mas
// this is the important thing:
self.tv.linkTextAttributes = [:]

The problem with UITextView linkTextAttributes is that it applies to all automatically detected links. What if you want different links to have different attributes?

It turns out there's a trick: configure the links as part of the text view's attributed text, and set the linkTextAttributes to an empty dictionary.

Here's an example in iOS 11 / Swift 4:

// mas is the mutable attributed string we are forming...
// ... and we're going to use as the text view's `attributedText`
mas.append(NSAttributedString(string: "LINK", attributes: [
    NSAttributedStringKey.link : URL(string: "https://www.apple.com")!,
    NSAttributedStringKey.foregroundColor : UIColor.green,
    NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]))
// ...
self.tv.attributedText = mas
// this is the important thing:
self.tv.linkTextAttributes = [:]
开始看清了 2024-08-09 20:08:19

Swift 5 Answer

很好很简单

myTextView.linkTextAttributes = [.foregroundColor: UIColor.white]

Swift 5 Answer

Nice and simple

myTextView.linkTextAttributes = [.foregroundColor: UIColor.white]
女中豪杰 2024-08-09 20:08:19

您可以通过以下方式更改 TextView 中的超链接颜色:

在 Nib 文件中,您可以转到“属性”窗口并将色调更改为您想要的颜色。

或者您也可以使用以下代码以编程方式完成此操作

[YOURTEXTVIEW setTintColor:[UIColor whiteColor]];

You can Change the Hyperlink Color in a TextView by the following:

In the Nib file, you can go to the Properties Window and change the Tint to which ever color you want to.

or you can also do it programatically by using the below code

[YOURTEXTVIEW setTintColor:[UIColor whiteColor]];
七月上 2024-08-09 20:08:19

色调颜色也可以在故事板中完成

在此处输入图像描述

The tint color can be done in the storyboard also

enter image description here

欲拥i 2024-08-09 20:08:19

我确实找到了另一种方法不使用网络视图,但请记住,这使用私有API,并且可能会在应用商店中被拒绝:

编辑:我的应用程序虽然私有api使用得到了苹果的批准!

首先使用方法在 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];
}

它确实在所有类型的链接上设置具有特定颜色的样式属性。

UITextViews 像通过 div 一样渲染 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" 是指示链接确切类型的指示器。链接

编辑

iOS7上这不再起作用。在 iOS7 中,您可以通过设置色调颜色轻松更改 UITextViews 的链接颜色。你不应该

- (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];

}
}

I found indeed another way without using a webview but keep in mind that this uses private API and may be rejected in appstore:

EDIT: My app got approved by apple although the private api usage!

First declare a category on UITextView with the methods

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

They are just doing the following:

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

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

Now write a method for colorful links:

- (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];
}

It does set the style attribute with a specific color on all types of links.

UITextViews are rendered Webiview like via divs so you could even go further and color each link type separately:

<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>

The x-apple-data-detectors-type="link" is the indicator for the exact type of the link

EDIT

On iOS7this is no longer working. In iOS7 you could easily change the link color of UITextViews by setting the tint color. You should not call

- (id)contentAsHTMLString;

anymore, you'll get an exception. Instead do the following if you want to support iOS 7 and below:

- (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];

}
}
书信已泛黄 2024-08-09 20:08:19

编辑:
不要使用 UITextView 执行此操作,而使用 UIWebView 代替。

您需要为此制作一个样式表。在那里定义一个具有您需要的颜色组合的类 -

.headercopy {
 font-family: "Helvetica";
 font-size: 14px;
 line-height: 18px;
 font-weight:bold;
 color: #25526e;
}
a.headercopy:link {
 color:#ffffff;
 text-decoration:none;
}
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}
a.headercopy:visited {
 color:#ffffff;
 text-decoration:none;
} 
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}

现在将类“headercopy”使用到您的 html 页面中,如下所示 -

<b>Fax:</b><a href="tel:646.200.7535" class="headercopy"> 646-200-7535</a><br />

这将以您需要的颜色显示电话号码并具有点击功能。

EDIT:
Don't do it with UITextView, use UIWebView instead.

You need to make a stylesheet for that. Define a class there with the color combination you need-

.headercopy {
 font-family: "Helvetica";
 font-size: 14px;
 line-height: 18px;
 font-weight:bold;
 color: #25526e;
}
a.headercopy:link {
 color:#ffffff;
 text-decoration:none;
}
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}
a.headercopy:visited {
 color:#ffffff;
 text-decoration:none;
} 
a.headercopy:hover {
 color:#00759B;
 text-decoration:none;
}

now use the class 'headercopy' into you html page like this-

<b>Fax:</b><a href="tel:646.200.7535" class="headercopy"> 646-200-7535</a><br />

this will display the phone number in the color you need with click functionality.

遗弃M 2024-08-09 20:08:19

此代码将设置 I-Phone 上电话号码的颜色,但会使自动呼叫链接无效。

<div><a href="#" x-apple-data-detectors="true" style="color:white;" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">p  0232 963 959</a></div>

This code will set the colour of a phone number on an I-Phone but voids the automatic call link.

<div><a href="#" x-apple-data-detectors="true" style="color:white;" x-apple-data-detectors-type="link" x-apple-data-detectors-result="0">p  0232 963 959</a></div>
故事未完 2024-08-09 20:08:19

这就是我使用 Swift 5 的方法:

let attributedString = NSMutableAttributedString(string: myTextView.text ?? "")
myTextView.linkTextAttributes = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.whiteColor] as [NSAttributedString.Key: Any]?
myTextView.attributedText = attributedString

This is how I did it using Swift 5:

let attributedString = NSMutableAttributedString(string: myTextView.text ?? "")
myTextView.linkTextAttributes = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.whiteColor] as [NSAttributedString.Key: Any]?
myTextView.attributedText = attributedString
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文