Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

ios7 - UILabel and NSLinkAttributeName: Link is not clickable

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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

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

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

UPDATE:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...