In my app, i have two textfields(username and Password) and UIbutton in SignIn page.

I want to enable button if textfield(password) having text.

I have created the UITextfield and UIbutton with below property in viewDidLoad().

 self.txtFieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
[self.btnLogin setEnabled:NO];

I have tried the below code and there is no luck.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.txtFieldPassword) {

    // checking for any whitespaces
    if(([string rangeOfString:@" "].location != NSNotFound))
    {
        return NO;
    }  

    if( [[self.txtFieldPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] )
        self.btnLogin.enabled = YES;
    else
        self.btnLogin.enabled = NO;
}

return YES;
}

but, if i removed the below line in UitextField means, it have worked.

self.txtFieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;

i want to enable button with the above property. How to achieve it?

Thanks!!!

有帮助吗?

解决方案

You can just check for string.length == 0 and range.length > 0; this denotes a deletion. However what you really want is to just do the pending modification and then check that you still have a non-empty string.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *testString = [textField.text stringByReplacingCharactersInRange:range withString:string];
testString = [testString stringByTrimmingCharactersInSet:
              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if( testString.length)
    myButton.enabled = YES;
else
    myButton.enabled = NO;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
 _done_button.enabled = NO;
  return YES;
}

you can achieve this with self.txtFieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing; property. it is working fine for me, have a great day

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top