【问题标题】:How to detect taps on underscores in a UITextView?如何检测 UITextView 中下划线的点击?
【发布时间】:2018-02-04 17:00:18
【问题描述】:

我有一个UITextView,其中某些单词被下划线替换,以填补空白。我很难检测到这些“空白”上的水龙头。到目前为止,我尝试的是使用 rangeEnclosingPosition 将“粒度”设置为 Word 来获取被点击的单词的范围,但看起来它无法识别对特殊字符的点击。现在,我希望为我的“下划线”字符串提供自定义属性,这样我就可以检查被点击的单词是否设置了任何自定义属性。任何想法都会非常有帮助。

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    这就是我的做法 -

    为文本中的特殊字符添加自定义属性。就我而言,我知道特殊字符都是下划线,或者这只是我想要的。所以我通过以下方式添加了一个自定义属性 -

    NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:underscoreString attributes:@{ @"yourCustomAttribute" : @"value", NSFontAttributeName : [ UIFont boldSystemFontOfSize:22.0] }];
    

    要查找对特殊字符的点击,请按以下方式添加UITapGestureRecognizer -

    UITapGestureRecognizer *textViewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedTextView:)];
    textViewTapRecognizer.delegate = self;
    [self.textView addGestureRecognizer:textViewTapRecognizer];
    

    并以下列方式定义其选择器 -

    -(void) tappedTextView:(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];
    NSString *value;
    if (characterIndex < textView.textStorage.length) {
        NSRange range;
        value = [[textView.attributedText attribute:@"yourCustomAttribute" atIndex:characterIndex effectiveRange:&range] intValue];
        NSLog(@"%@, %lu, %lu", value, (unsigned long)range.location, (unsigned long)range.length);
    }
    }
    

    如果你得到一个值,你的特殊字符被点击了。可能有更好的方法可以做到这一点,但目前这对我有用。

    【讨论】:

      【解决方案2】:

      您可以尝试使用 UITextViewDelegate 方法 - textViewDidChangeSelection 在文本视图中插入符号的位置发生变化时收到通知,如果插入符号当前位置的下一个字符是您的特殊字符,则在此处执行您的逻辑。

      【讨论】:

      • 我希望检测对特殊字符的点击。输入一个特殊字符会很容易:D
      • 我将在这里发布我在短时间内所做的事情:)
      猜你喜欢
      • 1970-01-01
      • 2013-09-13
      • 2012-06-12
      • 2012-10-18
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      相关资源
      最近更新 更多