在 UITextView 中点击 NSLinkAttributeName 链接在 iOS 9 中不起作用

paj*_*vic 0 objective-c uitextview nsattributedstring ios ios9

我有一个UITextView带有属性的文本,其设置如下:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is a message.\nClick here for more info"];
textView.linkTextAttributes = @{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
NSRange linkRange = [attributedString.string rangeOfString:@"Click here for more info"];
[attributedString addAttribute:NSLinkAttributeName value:@"" range:linkRange];
textView.attributedText = attributedString;
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoTapped:)];
[textView addGestureRecognizer:tapRecognizer
Run Code Online (Sandbox Code Playgroud)

然后我抓住了这样的水龙头:

- (void)infoTapped:(UITapGestureRecognizer *)tapGesture {
    if (tapGesture.state != UIGestureRecognizerStateEnded) {
        return;
    }

    UITextView *textView = (UITextView *)tapGesture.view;
    CGPoint tapLocation = [tapGesture locationInView:textView];
    UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
    NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
    NSString *link = attributes[NSLinkAttributeName];

    if (link) {
        // Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

在 iOS 10 中,这工作正常,我能够检测到该NSLinkAttributeName属性。但是,在 iOS 9 中调用[textView closestPositionToPoint:tapLocation]返回nil,我无法从那里做任何事情。

顺便提一句。我的 textview 有editableselectable设置为 NO。我知道有人说selctable需要将其设置为 YES,但我不确定这是真的。首先,它在 iOS 10 中没有可选的情况下工作正常。其次,如果我将它设置为可选,它确实可以工作,但只是有点。我确实在 iOS 9 中获得了点击,但它只能不稳定地工作(在 9 和 10 中)。有时它会注册水龙头,有时则不会。基本上,当我看到链接突出显示时,就像您在浏览器中单击链接一样,它不会注册。此外,现在可以选择我不想要的文本视图中的文本。

小智 5

为什么要使用点击手势选择链接?UITextView 具有完善的链接识别功能。我无法回答为什么您的解决方案在 iOS 9 上无法正常工作,但我可以建议您以另一种方式处理链接。这也适用于 iOS 9。

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"This is a message.\nClick here for more info" attributes:nil];
NSRange range = [str.string rangeOfString:@"Click here for more info"];
// add a value to link attribute, you'll use it to determine what link is tapped
[str addAttribute:NSLinkAttributeName value:@"ShowInfoLink" range:range];
self.textView.linkTextAttributes = @{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)};
self.textView.attributedText = str;
// set textView's delegate
self.textView.delegate = self;
Run Code Online (Sandbox Code Playgroud)

然后实现 UITextViewDelegate 的链接相关方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
    if ([URL.absoluteString isEqualToString:@"ShowInfoLink"]) {
        // Do something
    }
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

要使其工作,您必须设置 selectable = YES 并检查故事板中的链接标志才能检测链接。