den*_*kov 4 objective-c nsstring uitextview ios
我一直在寻找高低,无法弄清楚如何做到这一点。假设我有一个这样的字符串:
NSString *string = @"&foo !foo";
Run Code Online (Sandbox Code Playgroud)
我想要做的是区分文本视图中的两个 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];
Run Code Online (Sandbox Code Playgroud)
我不知道如何获得前一个字符。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];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2469 次 |
| 最近记录: |