UILabel和NSLinkAttributeName:链接不可单击 [英] UILabel and NSLinkAttributeName: Link is not clickable

查看:930
本文介绍了UILabel和NSLinkAttributeName:链接不可单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用带有 NSLinkAttributeName 的属性字符串在我的iOS 7项目中的 UILabel 实例中创建可点击链接,现在终于可以不使用外部库了。

I want to use attributed strings with NSLinkAttributeName to create clickable links inside a UILabel instance within my iOS 7 project, which is now finally possible without using external libraries.

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];

NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                          url, NSLinkAttributeName, nil];

在字符串上应用该属性会将文本显示为蓝色&带下划线,但点击/点击没有任何反应。为标签启用了用户交互。
有人知道怎么做吗?谢谢!

Applying the attribute on a string displays the text as blue & underlined, but nothing happens on click/tap. User interaction is enabled for the label. Does anybody know how to do this? Thanks!

推荐答案

我现在可以回答我自己的问题:
我正在使用 UITextView 而不是 UILabel 现在。我已将 UITextView 的格式设置为外观和行为,如我的标签并添加:

I can answer my own question now: I am using UITextView instead of UILabel now. I have formatted the UITextView to look and behave like my labels and added:

UITextView *textView = [[UITextView alloc] init];
textView.scrollEnabled = NO;
textView.editable = NO;
textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
textView.delegate = self;

不要忘记设置委托,你必须实现 UITextViewDelegate !现在我们实现委托方法:

Don't forget to set the delegate, you have to implement UITextViewDelegate! Now we implement the delegate method:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
{
     return YES;
}

这会自动打开提供的 NSURL -instance来自我在点击/点按的问题中的属性字符串。

This automatically opens the provided the NSURL-instance from the attributed string in my question on click/tap.

请记住:这仅适用于iOS 7,对于旧版支持,您需要外部库

Remember: This works on iOS 7 only, for legacy support you need external libraries

更新:

制作 UITextView s的行为就像标签最终一团糟,我偶然发现了一些丑陋的iOS行为。我最终使用了 TTTAttributedLabel 库,这非常棒,允许我使用标签代替 UITextView s。

Making the UITextViews behave just like labels was a total mess in the end and i stumbled upon some hideous iOS-behaviours. I ended up using the TTTAttributedLabel library which is simply great and allowed me to use labels instead of UITextViews.

这篇关于UILabel和NSLinkAttributeName:链接不可单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆