Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor location in a uitextfield

im using customkeyboard in my controller. but how to get the cursor location in the uitextfiled. my requirement is to enter a charecter in a desired location of textfield. is it possible?

like image 926
Allen Avatar asked Feb 03 '26 09:02

Allen


1 Answers

Let's assume that you code is in a method on an object where self.textField is the UITextField in question.

You can find the current position of the cursor/selection with:

NSRange range = self.textField.selectedTextRange;

If the user has not selected text the range.length will be 0, indicating that it is just a cursor. Unfortunately this property does not appear to be KVO compliant, so there is no efficient way to be informed when it changes, however this should not be a problem in your case because you probably really only care about it when you are responding to user interaction with your custom keyboard.

You can then use (assuming newText holds the input from your custom keyboard).

[self.textField replaceRange:range withText:newText];

If you need to subsequently adjust the cursor/selection you can use:

self.textField.selectedTextRange = newRange;

For example, you may want to position the cursor after the text you inserted.

UPDATE:

In my original answer I failed to notice that I was leveraging a category I had added to UITextView:

- (void)setSelectedRange:(NSRange)selectedRange
{
    UITextPosition* from = [self positionFromPosition:self.beginningOfDocument offset:selectedRange.location];
    UITextPosition* to = [self positionFromPosition:from offset:selectedRange.length];
    self.selectedTextRange = [self textRangeFromPosition:from toPosition:to];
}

- (NSRange)selectedRange
{
    UITextRange* range = self.selectedTextRange;
    NSInteger location = [self offsetFromPosition:self.beginningOfDocument toPosition:range.start];
    NSInteger length = [self offsetFromPosition:range.start toPosition:range.end];
    NSAssert(location >= 0, @"Location is valid.");
    NSAssert(length >= 0, @"Length is valid.");
    return NSMakeRange(location, length);
}

Then replace use self.textField.selectedRange instead of self.textField.selectedTextRange and proceed as I described.

Thanks to omz for pointing out my error.

Of course, you can work directly with UITextRange but, at least in my case, this proved to be rather ungainly.

like image 141
idz Avatar answered Feb 04 '26 23:02

idz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!