Disabling the caret and text entry in UITextFields

Guides | Tutorial By 3 years ago

If you set the UITextField inputView to a UIPickerView, UIDatePicker or custom view, you may want to disable the caret in the UITextField.

You will probably also want to stop the user from entering in any text or copying, selecting or pasting any text into the UITextField. This way the only input into the UITextField is from the inputView.

To achieve this, add the following code the the UITextField subclass.


- (CGRect) caretRectForPosition:(UITextPosition*) position
{
    return CGRectZero;
}

- (NSArray *)selectionRectsForRange:(UITextRange *)range
{
    return nil;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(copy:) || action == @selector(selectAll:) || action == @selector(paste:))
    {
        returnNO;
    }

    return [super canPerformAction:action withSender:sender];
}