How to enable a UIButton if a textfield is not empty?
I'm having a problem with my UITextField and three UIButtons. I want to disable the buttons when the UITextfield is empty and re-enable when it has text on it. I already tried this:
- (IBAction)validateFields:(id)sender {
NSString *trimName = [URLToTrim stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (trimName.length >0)
{
trim.enabled = 1;
trim2.enabled = 1;
trim3.enabled =1;
// proceed with your inserting values
}
}
And this:
-(void)viewDidLoad {
if([URLToTrim.text isEqualToString: @""]){
trim.hidden = YES;
trim2.hidden = YES;
trim3.hidden = YES;
} else {
trim.hidden = NO;
trim2.hidden = NO;
trim3.hidden = NO;
}
and lastly, this:
-(void)viewDidLoad {
if ([URLToTrim.text isEqualToString:@""]) {
trim.enabled = 0;
trim2.enabled= 0;
trim3.enabled = 0;
}
But with the first one the app cr开发者_开发百科ashes when writing and with the second one the buttons aren't being re-enabled. Thanks in advance for the help :)
It seems URLToTrim is a UITextField? The problem in the first is that you're calling stringByTrimmingCharactersInSet:
on the text field itself, instead of the value of the text field. You do it right in the other two, using URLToTrim.text
.
The problem with the second is that viewDidLoad
is only called when the view is first loaded, so it never gets called again to re-enable the buttons. You want to do that code in one of the methods of your UITextFieldDelegate (which may already be your same view controller), probably textField:shouldChangeCharactersInRange:replacementString:
although textFieldShouldEndEditing:
/textFieldDidEndEditing:
could work if you only want the buttons to be updated when you finish editing.
精彩评论