[英]How to detect taps on underscores in a UITextView?
我有一个UITextView
其中某些单词被下划线替换,以填补空白效果。 我在检测这些“空白”上的水龙头时遇到困难。 到目前为止,我已经尝试过使用Granularity设置为Word的rangeEnclosingPosition
来获取被敲击的单词的范围,但是看起来它无法识别特殊字符的敲击。 现在,我希望为我的“下划线”字符串提供自定义属性,以便随后可以查看是否点击的单词设置了任何自定义属性。 任何想法都将对您有所帮助。
您可以尝试使用UITextViewDelegate方法-textViewDidChangeSelection ,当插入符在文本视图中的位置发生更改时得到通知,如果插入符当前位置的下一个字符是您的特殊字符,请在此处进行逻辑处理。
这是我的做法-
将自定义属性添加到文本中的特殊字符。 就我而言,我知道特殊字符都是下划线,或者这仅仅是我要的内容。 因此,我通过以下方式添加了自定义属性-
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);
}
}
如果您得到一个值,则说明您的特殊字符被点击。 可能有更好的方法可以执行此操作,但现在对我而言有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.