使用UITextPosition,从textInRange获取前一个字符

时间:2014-05-12 11:33:37

标签: ios objective-c nsstring uitextview

我一直在寻找高低,无法弄清楚如何做到这一点。假设我有一个这样的字符串:

NSString *string = @"&foo !foo";

我想要做的是区分文本视图中的两个foos(听起来很有趣哈哈)。当我点击一个时,我想知道它前面有哪个(&或!)。这是我得到这个词的方式:

UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
UITextView *TV = (UITextView*)recognizer.view;
CGPoint location = [recognizer locationInView:TV];
location.y += TV.contentOffset.y;
UITextPosition *tapPosition = [TV closestPositionToPoint:CGPointMake(location.x, location.y)];
UITextRange *textRange = [TV.tokenizer rangeEnclosingPosition:tapPosition 
    withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
NSString *tappedWord = [TV textInRange:textRange];

我无法弄清楚如何获得前一个角色。 TV.tokenizer UITextGranularityCharacter只获得最接近的字母,而不是符号。对此有何解决方案?

1 个答案:

答案 0 :(得分:4)

检查:Convert selectedTextRange UITextRange to NSRange将您的UITextRange转换为NSRange(我打电话给selectedRange)。

根据之前对相关问题的回答激励我,您需要在代码末尾添加此内容:

UITextPosition *beginning = TV.beginningOfDocument;
UITextPosition *selectionStart = textRange.start;
UITextPosition *selectionEnd = textRange.end;
NSInteger location = [TV offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [TV offsetFromPosition:selectionStart toPosition:selectionEnd];
NSRange selectedRange = NSMakeRange(location,lenght);
NSRange range = NSMakeRange(selectedRange.location-1,1) //Maybe need to check if selectedRange.location>0
NSString *yourCharString = [[TV text] substringWithRange:range];