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

查看:99
本文介绍了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;

别忘了设置delegate,你要实现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 实例.

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 的行为就像标签一样最终是一团糟,我偶然发现了一些可怕的 iOS 行为.我最终使用了 TTTAttributedLabel 库,它非常棒,允许我使用标签而不是 UITextViews.

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天全站免登陆