I understand this question has been asked before, but I'm not satisfied with the answers, i.e. by making it disabled. There is a fundamental difference: Disabled view doesn't fire events, but for a read-only view, it should still fire event like (e.g. TouchUpInside), and I need it. Only thing I don't want is the keyboard input.
The reason is that I have several input fields, some can useUITextField
directly, others are not. I want to have them look similar. So, I'd like to use UITextField
to display all of them. Some of them need to be read-only so that I can use touch up event for alternative input.
Or there might be a completely different way to do it?
EDIT: This is for my MonoTouch project. I have very limited knowledge of Objective-c.
Say you have 2 text field instance variables connected to text fields you created in the Interface Builder. Lets call them myReadOnlyTextField
and myEditableTextField
. Make sure you connect the delegate
property of each text field in the Interface Builder to the view controller ("File's Owner")[1]. Now, in the view controller @implementation
(.m file), use the method textFieldShouldBeginEditing:
and put in some logic to determine which text field you want to allow editing and which to not allow editing; something like this:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
BOOL editable;
if (textField == myReadOnlyTextField) {
editable = NO;
} else if (textField == myEditableTextField) {
editable = YES;
} else {
// editable = YES/NO/Other Logic
}
return editable;
}
From the UITextFieldDelegate
Documentation:
textFieldShouldBeginEditing:
Asks the delegate if editing should begin in the specified text field.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
Parameters
textField
- The text field for which editing is about to begin.Return Value
YES
if an editing session should be initiated; otherwise,NO
to disallow editing.Discussion
When the user performs an action that would normally initiate an editing session, the text field calls this method first to see if editing should actually proceed. In most circumstances, you would simply return YES from this method to allow editing to proceed.Implementation of this method by the delegate is optional. If it is not present, editing proceeds as if this method had returned YES.
UITextField
Documentation is a good read also.
[1] You can do this programmatically as well. Here is an example:
- (void)viewDidLoad {
[super viewDidLoad];
// .....
myReadOnlyTextField.delegate = self;
myEditableTextField.delegate = self;
}