2017-08-27 78 views
0

我有一个UITextView某些单词被下划线替换为填充空白效果。我在检测这些“空白”上点击时遇到困难。我到目前为止所尝试的是使用rangeEnclosingPosition的“粒度设置为Word”来获取单词的范围,但看起来它不能识别特殊字符上的点击。现在,我正在寻找给我的'下划线'字符串自定义属性,所以我可以检查,看看是否有任何自定义属性设置。任何想法都会很有帮助。如何检测UITextView下划线的水龙头?

回答

0

您可以尝试使用UITextViewDelegate方法 - textViewDidChangeSelection通知时插入符号的文本视图的位置发生变化,使你的逻辑在这里如果从插入符号的当前位置的下一个字符是你的特殊字符。

+0

我想检测一个特殊字符的水龙头。键入一个特殊的字符本来就很容易:D – genaks

+0

我会在这里发布我在短时间内做的事:) – genaks

0

以下是我如何做到的 -

将自定义属性添加到文本中的特殊字符。就我而言,我知道特殊字符将全部是下划线,或者这只是我所寻找的。

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); 
} 
} 

如果您得到一个值,您的特殊字符被点击。可以有更好的方法来做到这一点,但现在这对我来说很有效。