The location of the cursor in the uitextfield field

im using customkeyboard in my controller. but how to get cursor location in uitextfiled file. my requirement is to enter the charecter in the right place in the text box. Is it possible?

+3
source share
3 answers

Suppose you code is in an object method, where self.textFieldis the UITextField in question.

You can find the current cursor / selection position with:

NSRange range = self.textField.selectedTextRange;

, range.length 0, , . , KVO, , , , , , .

( , newText ).

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

/, :

self.textField.selectedTextRange = newRange;

, .

:

, , 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);
}

self.textField.selectedRange self.textField.selectedTextRange , .

omz .

, UITextRange, , , .

+1

, , . [textField paste], , , , .

, , , .

0

Swift

Get cursor location:

if let selectedRange = textField.selectedTextRange {
    let cursorPosition = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: selectedRange.start)
}

Enter the text in any place:

let arbitraryValue: Int = 5
if let newPosition = textField.positionFromPosition(textField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: arbitraryValue) {

    textField.selectedTextRange = textField.textRangeFromPosition(newPosition, toPosition: newPosition)
    textField.insertText("Hello")
}

My complete answer is here .

0
source

Source: https://habr.com/ru/post/1744277/


All Articles