检测UITextView中的字符
我使用下面的代码来检测在UITextView中点击的单词。 这工作正常,但我想检测一些特殊字符,如?
。 ?
在使用UITextGranularityWord
时不会显示为单词的一部分,而且在使用UITextGranularityWord
时也看不到它。
我如何检测单个特殊字符,如?
?
-(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv { //eliminate scroll offset pos.y += _tv.contentOffset.y; //get location in text from textposition at point UITextPosition *tapPos = [_tv closestPositionToPoint:pos]; //fetch the word at this position (or nil, if not available) UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight]; if ([_tv textInRange:wr].length == 0) {//ie it's not a word NSLog(@"is 0 length, check for characters (eg ?)"); UITextRange *ch = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight]; NSLog(@"ch range: %@ ch text: %@",ch, [_tv textInRange:ch] ); // logs: ch range: (null) ch text: if ([[_tv textInRange:ch] isEqualToString:@"?"]) { return [_tv textInRange:ch]; } } return [_tv textInRange:wr]; }
此代码在iOS 6上适用于我:
- (void)tappedTextView:(UITapGestureRecognizer *)recognizer { UITextView *textView = (UITextView *)recognizer.view; CGPoint location = [recognizer locationInView:textView]; UITextPosition *tapPosition = [textView closestPositionToPoint:location]; UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight]; NSString *character = [textView textInRange:textRange]; NSLog(@"%@", character); }