34

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!

4

1 回答 1

49

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

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!现在我们实现委托方法:

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

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

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

更新:

UITextViews 表现得像标签一样最终是一团糟,我偶然发现了一些可怕的 iOS 行为。我最终使用了TTTAttributedLabel库,它非常棒,允许我使用标签而不是UITextViews。

于 2013-11-08T10:26:15.357 回答