创建可点击的“链接";在 UILabel 的 NSAttributedString 中?

Create tap-able quot;linksquot; in the NSAttributedString of a UILabel?(创建可点击的“链接;在 UILabel 的 NSAttributedString 中?)
本文介绍了创建可点击的“链接";在 UILabel 的 NSAttributedString 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了几个小时,但我失败了.我可能什至不知道我应该寻找什么.

I have been searching this for hours but I've failed. I probably don't even know what I should be looking for.

许多应用程序都有文本,并且在此文本中是圆角矩形的 Web 超链接.当我单击它们时 UIWebView 打开.令我困惑的是,它们通常具有自定义链接,例如,如果单词以 # 开头,它也是可点击的,并且应用程序通过打开另一个视图来响应.我怎样才能做到这一点?是否可以使用 UILabel 还是我需要 UITextView 或其他东西?

Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView opens. What puzzles me is that they often have custom links, for example if words starts with # it is also clickable and the application responds by opening another view. How can I do that? Is it possible with UILabel or do I need UITextView or something else?

推荐答案

一般来说,如果我们想让 UILabel 显示的文本中有一个可点击的链接,我们需要解决两个独立的任务:

In general, if we want to have a clickable link in text displayed by UILabel, we would need to resolve two independent tasks:

  1. 将部分文本的外观更改为看起来像一个链接
  2. 检测和处理对链接的触摸(打开 URL 是一种特殊情况)

第一个很简单.从 iOS 6 开始,UILabel 支持属性字符串的显示.您需要做的就是创建和配置 NSMutableAttributedString 的实例:

The first one is easy. Starting from iOS 6 UILabel supports display of attributed strings. All you need to do is to create and configure an instance of NSMutableAttributedString:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"String with a link" attributes:nil];
NSRange linkRange = NSMakeRange(14, 4); // for the word "link" in the string above

NSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0],
                                  NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };
[attributedString setAttributes:linkAttributes range:linkRange];

// Assign attributedText to UILabel
label.attributedText = attributedString;

就是这样!上面的代码使 UILabel 显示带有 链接

That's it! The code above makes UILabel to display String with a link

现在我们应该检测到此链接上的触摸.这个想法是捕捉 UILabel 中的所有点击,并确定点击的位置是否足够靠近链接.为了捕捉触摸,我们可以将点击手势识别器添加到标签中.确保为标签启用 userInteraction,默认情况下它是关闭的:

Now we should detect touches on this link. The idea is to catch all taps within UILabel and figure out whether the location of the tap was close enough to the link. To catch touches we can add tap gesture recognizer to the label. Make sure to enable userInteraction for the label, it's turned off by default:

label.userInteractionEnabled = YES;
[label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnLabel:)]]; 

现在最复杂的东西:找出点击是否在显示链接的位置,而不是在标签的任何其他部分.如果我们有单行 UILabel,这个任务可以通过硬编码链接显示的区域边界来相对容易地解决,但是让我们更优雅地解决这个问题,并且对于一般情况 - 多行 UILabel 没有关于链接布局的初步知识.

Now the most sophisticated stuff: finding out whether the tap was on where the link is displayed and not on any other portion of the label. If we had single-lined UILabel, this task could be solved relatively easy by hardcoding the area bounds where the link is displayed, but let's solve this problem more elegantly and for general case - multiline UILabel without preliminary knowledge about the link layout.

其中一种方法是使用 iOS 7 中引入的 Text Kit API 的功能:

One of the approaches is to use capabilities of Text Kit API introduced in iOS 7:

// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];

// Configure layoutManager and textStorage
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

// Configure textContainer
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = label.lineBreakMode;
textContainer.maximumNumberOfLines = label.numberOfLines;

将创建和配置的 NSLayoutManager、NSTextContainer 和 NSTextStorage 实例保存在您的类(很可能是 UIViewController 的后代)的属性中 - 我们将在其他方法中需要它们.

Save created and configured instances of NSLayoutManager, NSTextContainer and NSTextStorage in properties in your class (most likely UIViewController's descendant) - we'll need them in other methods.

现在,每次标签更改其框架时,都会更新 textContainer 的大小:

Now, each time the label changes its frame, update textContainer's size:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.textContainer.size = self.label.bounds.size;
}

最后,检测是否点击了链接:

And finally, detect whether the tap was exactly on the link:

- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture
{
    CGPoint locationOfTouchInLabel = [tapGesture locationInView:tapGesture.view];
    CGSize labelSize = tapGesture.view.bounds.size;
    CGRect textBoundingBox = [self.layoutManager usedRectForTextContainer:self.textContainer];
    CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
    CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                         locationOfTouchInLabel.y - textContainerOffset.y);
    NSInteger indexOfCharacter = [self.layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                            inTextContainer:self.textContainer
                                   fractionOfDistanceBetweenInsertionPoints:nil];
    NSRange linkRange = NSMakeRange(14, 4); // it's better to save the range somewhere when it was originally used for marking link in attributed string
    if (NSLocationInRange(indexOfCharacter, linkRange)) {
        // Open an URL, or handle the tap on the link in any other way
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://stackoverflow.com/"]];
    }
}

这篇关于创建可点击的“链接";在 UILabel 的 NSAttributedString 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)