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

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

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只获取最接近的字母,而不是符号。 对此有何解决方案?

检查: 将selectedTextRange UITextRange转换为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];