Is there an easy way to disable a UITextField
in code?
My app has 12 UITextField
that are all turned on by default, but when a change is de
This would be the simplest of all , when you multiple textfields too:
in viewDidLoad:(set the delegate only for textfields which should not be editable.
self.textfield.delegate=self;
and insert this delegate function:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return NO;
}
Thats it!
In Objective-C:
textField.enabled = NO;
In Swift:
textField.isEnabled = false
Reference: UIControl.isEnabled
You should conform to UITextFieldDelegate
and return false
in this method. This way the text field is still selectable, but it is not available for editing and cutting
Code is in Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return false
}
Make category on UIView.
add following methods in that category.
-(void)disable {
self.alpha = 0.5;
self.userInteractionEnabled = FALSE;
}
-(void)enable {
self.alpha = 1.0;
self.userInteractionEnabled = TRUE;
}
then just call
yourTextField.disable();
Actually,You can use this on any view that you want.
If you also want to indicate that the text field is disabled you should add more code:
if using UITextBorderStyleRoundedRect, you can only gray out text:
textField.enabled = NO;
textField.textColor = [UIColor lightGrayColor];
if using any other style, you can also gray out background:
textField.enabled = NO;
textField.backgroundColor = [UIColor lightGrayColor];