Search code examples
ios7uitextviewuitextpositionuitextrange

UITextView get previous character - (i.e character before the cursor position) (iOS7)


I can't work out how I can get the previous character that was entered. so in other words how can I get the character that is just before the cursor any where inside the UITextView.

NSInteger pos = [self.textInput offsetFromPosition:self.textInput.beginningOfDocument toPosition:textrange.start];

CGRect s = [self.textInput caretRectForPosition:self.textInput.selectedTextRange.start];

UITextRange *textrange = [self.textInput characterRangeAtPoint: s.origin];

Thanks,

Kind Regards,

Will


Solution

  • Thanks it is what I was looking for, I did see it before actually but was not 100% sure, I modified it slightly and its good.

        UITextPosition *beginning = self.textInput.beginningOfDocument;
        UITextPosition *selectionStart = self.textInput.selectedTextRange.start;
        UITextPosition *selectionEnd = self.textInput.selectedTextRange.end;
        NSInteger location = [self.textInput offsetFromPosition:beginning toPosition:selectionStart];
        NSInteger length = [self.textInput offsetFromPosition:selectionStart toPosition:selectionEnd];
        NSRange selectedRange = NSMakeRange(location,length);
        NSRange range = NSMakeRange(selectedRange.location-1,1);
    
        NSString *lastChar = [textValue substringWithRange:range];