Disable cursor and copy/paste in UITextView (swift)

rgamber picture rgamber · Feb 9, 2015 · Viewed 10.1k times · Source

I have a UITextField for which I am using UIPickerView as its inputView. The user can select a value from the picker, and the selected value gets populated into my TextInput.
This arrangement works fine, but with the following issues:

1) I want to disable the cursor that still shows in the UITextField.
I tried disabling the UITextField, but then it does not respond to touches and then the UIPickerView does not show - which makes it useless.
2) Since the picker is shown and the keyboard is not wen the user taps on the text-field, the user cannot type anything, but still can paste text copied from else where by long pressing. How can I disable this?

I am not able to find the relevant information online. Should I be using a Label or a Button for this instead of the UITextInput?

Answer

TonyMkenu picture TonyMkenu · Feb 10, 2015

I think the easy way is to make it with a button instead UITextField

Sorry - this is not for Swift it's for Obj-C but this is the idea:

To do what you want with UITextField you have to subclass the UITextField and try to use this code to disable/hide caret and input (copy/paste)

- (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];
}

example from here: http://b2cloud.com.au/tutorial/disabling-the-caret-and-text-entry-in-uitextfields/

Anyway... this is a "functional" example: https://github.com/hackiftekhar/IQDropDownTextField