ios - 在 iOS 的 UITextView 中检测属性文本的点击

标签 ios objective-c uitextview textkit

我有一个显示 NSAttributedStringUITextView。该字符串包含我希望使其可点击的单词,这样当他们被点击时,我会被回调,以便我可以执行操作。我意识到 UITextView 可以检测 URL 上的点击并回调我的委托(delegate),但这些不是 URL。

在我看来,借助 iOS 7 和 TextKit 的强大功能,这现在应该是可能的,但是我找不到任何示例,我不知道从哪里开始。

我知道现在可以在字符串中创建自定义属性(尽管我还没有这样做),也许这些对于检测是否已点击其中一个魔术词很有用?无论如何,我仍然不知道如何拦截该点击并检测点击发生在哪个单词上。

请注意,不需要兼容 iOS 6。

最佳答案

我只是想多帮助别人一点。根据 Shmidt 的回答,可以完全按照我在原始问题中的要求进行操作。

1) 创建一个属性字符串,并将自定义属性应用于可点击的单词。例如。

NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"a clickable word" attributes:@{ @"myCustomTag" : @(YES) }];
[paragraph appendAttributedString:attributedString];

2) 创建一个 UITextView 来显示该字符串,并向其中添加一个 UITapGestureRecognizer。然后处理水龙头:

- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;

    // Location of the tap in text-container coordinates

    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];
    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;

    // Find the character that's been tapped on

    NSUInteger characterIndex;
    characterIndex = [layoutManager characterIndexForPoint:location
                                           inTextContainer:textView.textContainer
                  fractionOfDistanceBetweenInsertionPoints:NULL];

    if (characterIndex < textView.textStorage.length) {

        NSRange range;
        id value = [textView.attributedText attribute:@"myCustomTag" atIndex:characterIndex effectiveRange:&range];

        // Handle as required...

        NSLog(@"%@, %d, %d", value, range.location, range.length);

    }
}

知道怎么做就这么简单!

关于ios - 在 iOS 的 UITextView 中检测属性文本的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332283/

相关文章:

ios - 使用 Obejctive C 在 tableview 单元格中搜索特定值时如何获取所有数组值?

iphone - 调整标签在 UITableViewCell 中的位置

objective-c - 如何绘制半透明的NSTableRowView?

ios - 你能以编程方式修改 iPhone App Info.plist 中的 NSExceptionMinimumTLSVersion 吗?

iOS - UIToolBar 作为 UITextView 的 inputAccessoryView

ios - AVSampleBufferDisplayLayer 的快照

ios - 在 AutoLayout - iOS 中,约束计数始终为零 ( 0 )

android - 非技术业务用户的问题 : Storage on phone vs. 云存储

iOS 11 : UITextView typingAttributes reset when typing

objective-c - 添加 UITextview 时应用程序崩溃 "[UITextView length]: unrecognized selector sent to instance"