简体   繁体   中英

Disabled UIButton dependant on 4 UITextFields

I have 4 UITextFields that I am using to keep 2 UIButtons disabled until all 4 fields have data entered into them. I have the following code so far

- (void)textFieldDidBeginEditing:(UITextField *)textField {


if (([brand.text length] >0) && ([qty.text length] >0) && ([size.text length] >0) && ([price.text length] >0)) {
    [calcOneButton setEnabled:YES];
    [calcTwoButton setEnabled:YES];

}else {

}


}

I have a number of problems with this:-

  1. When data is removed from the fields the UIButtons are still enabled
  2. The Buttons arent enabling correctly, after I have entered data into all 4 fields I need to re-tap on a field to enable the button.
  3. I am logging the length of each field but as a character is entered it starts at a count of 0 not 1.

Can anyone help with these points?

The code for logging the length of a field is as follows:-

#define MAXLENGTH 5
#define MAXQTY 3
#define MAXSIZE 4
#define MAXBRAND 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == brand) {
    int lengtha = [brand.text length] ;
    NSLog(@"lenghta = %d",lengtha);
    if (lengtha >= MAXBRAND && ![string isEqualToString:@""]) {
        brand.text = [brand.text substringToIndex:MAXBRAND];
        return NO;
    }

it follows the same format for all 4 fields, but as I enter a character the NSlog results as a 0 then 1 for the second character and so on.

Just use another delegate-method.

Either use: textFieldDidEndEditing: like Krypton told you in a comment

or use textField:shouldChangeCharactersInRange:replacementString: for enable/disable directly when typing.

textField:(UITextField*)aTextField shouldChangeCharactersInRange:(NSRange) aRange replacementString:(NSString*)aRepString
{
    NSString *newStr = [aTextField.text stringByReplacingCharactersInRange:aRange withString:aRepString];
    if([newStr length]>0 && /*otherStringLength > 0*/)
          //enable
    else
          //disable
    return YES;
 }

But I think the most common way is to use the didEndEditing -method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM