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
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
}
Extension of @kas-kad's solution. I created a subclass of UITextView, with this
var enableCursorMotion = true
override func closestPosition(to point: CGPoint) -> UITextPosition? {
if enableCursorMotion {
return super.closestPosition(to: point)
}
else {
let beginning = self.beginningOfDocument
let end = self.position(from: beginning, offset: (self.text?.count)!)
return end
}
}
Ok, what you have to do is have a UITextField that is hidden.
Add that hidden text field to the view, and call becomeFirstResponder on it. From your amountBoxTouchDown: method.
In the Textfield delegate, take the text the user typed in and add it to amountBox.text. Also turn off userInteractionEnabled for the visible amountBox textField.
This creates the effect you desire.
Have a look at for some sample code Link.
Think in layers and of controls as tools that you can combine to achieve functionality.
If you simply place a UIButton over top a UITextField and change the button type to Custom, you can prevent all touch events on the text field such as moving the cursor, selecting text, copying, cutting, and pasting.
By default, a custom button is transparent.
Create an action so that when the button is touched, the text field becomes the first responder.
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 are interested in always keeping your cursor at the end of the text, do this:
override func closestPosition(to point: CGPoint) -> UITextPosition? {
return self.endOfDocument
}