簡體   English   中英

在UITextView中點擊NSLinkAttributeName鏈接在iOS 9中不起作用

[英]Tapping a NSLinkAttributeName link in UITextView not working in iOS 9

我有一個帶有屬性文本的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]至點[textView closestPositionToPoint:tapLocation]的調用返回nil[textView closestPositionToPoint:tapLocation]我將無法執行任何操作。

順便說一句。 我的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並檢查情節提要中的鏈接標志以能夠檢測到鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM