代码之家  ›  专栏  ›  技术社区  ›  pajevic

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

  •  0
  • pajevic  · 技术社区  · 7 年前

    我有一个 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
    

    然后我听到一个像这样的水龙头:

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

    在iOS 10中,这很好,我能够检测到 NSLinkAttributeName 属性 [textView closestPositionToPoint:tapLocation] 退货 nil 从那以后我什么都做不了。

    editable selectable 设置为否。我知道有人这么说 selctable

    1 回复  |  直到 7 年前
        1
  •  5
  •   Stas Volskiy    7 年前

    为什么要使用点击手势选择链接?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;
    

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

    要使其工作,您必须设置selectable=YES,并在情节提要中选中links标志,以便能够检测链接。