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
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With