Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from setting cursor position on UITextField

I have an UITextField constructed using the storyboard. I want to not allow the user to change the position of the cursor and keep it always at the end of the text into the text field.

I tried to change the position of the cursor at the touchdown event, but when selecting the text field and then change the position of the cursor by touching the text field again, the position is changed:

- (IBAction)amountBoxTouchDown:(id)sender {
    UITextPosition *start = [amountBox positionFromPosition:[amountBox beginningOfDocument] offset:amountBox.text.length];
    UITextPosition *end = [amountBox positionFromPosition:start
                                                   offset:0];
    [amountBox setSelectedTextRange:[amountBox textRangeFromPosition:start toPosition:end]];
}

Does anyone know a solution? Thanks

like image 459
MahdiS Avatar asked May 07 '13 12:05

MahdiS


2 Answers

Simply create a subclass of UITextField and override the closestPositionToPoint method:

- (UITextPosition *)closestPositionToPoint:(CGPoint)point{
    UITextPosition *beginning = self.beginningOfDocument;
    UITextPosition *end = [self positionFromPosition:beginning offset:self.text.length];
    return end;
}

Now the user will be unable to move cursor, it will be always in the end of field.

SWIFT:

override func closestPosition(to point: CGPoint) -> UITextPosition? {
    let beginning = self.beginningOfDocument
    let end = self.position(from: beginning, offset: self.text?.count ?? 0)
    return end
}
like image 192
kas-kad Avatar answered Sep 26 '22 09:09

kas-kad


Disable any gesture recognizers on the text field after it has become first responder. This allows it to receive the initial tap, but prevents the user from interacting with the field while it is the first responder. This keeps the system behavior of keeping the cursor at the end of the text without allowing the user to override it.

In a UITextField subclass, add the following:

SWIFT 3.1:

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return !isFirstResponder
}

In your storyboard, change the class of your text field to your UITextField subclass.

like image 23
Sean Kladek Avatar answered Sep 23 '22 09:09

Sean Kladek