我有一个带有属性文本的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属性。
但是,在iOS 9中,对[textView closestPositionToPoint:tapLocation]的调用返回了nil,从那以后我什么也不能做。

顺便说一句。我的textview的editableselectable都设置为NO。我知道有人说selctable需要设置为YES,但是我不确定这是真的。首先,它在iOS 10中不需要选择就可以正常工作。其次,如果我将其设置为可选择,它确实可以工作,但只能用于某种程度。我确实在iOS 9中获得了点击,但它只能正常运行(在9和10中)。有时它会记录水龙头,有时却不会。基本上,当我看到链接突出显示时,例如单击浏览器中的链接时,它不会注册。此外,现在可以选择不需要的文本视图中的文本。

最佳答案

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


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

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


为了使其正常工作,您必须设置selectable = YES并检查情节提要中的链接标志以能够检测到链接。

关于ios - 在UITextView中点击NSLinkAttributeName链接在iOS 9中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45711962/

10-12 01:23
查看更多