using UITextPosition, get previous character from textInRange

烈酒焚心 提交于 2019-12-01 06:28:24

问题


I've been searching high and low and can't figure out how to do this. Lets say I have a string like this:

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

What I'm trying to do is differentiate between the two foos (sounds funny haha) inside a text view. When I click on one, I want to know which (& or !) comes before it. Here's how I'm getting the word:

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];

I can't figure out how to get the previous character. TV.tokenizer UITextGranularityCharacter only gets the closest letter, not the symbol. Any solutions for this?


回答1:


Check: Convert selectedTextRange UITextRange to NSRange to convert your UITextRange to a NSRange (that I'll call selectedRange).

Inspiring me with the previous answer to the linked question, you'd need to add this at the end of your code:

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];


来源:https://stackoverflow.com/questions/23607883/using-uitextposition-get-previous-character-from-textinrange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!