开发者

How to require a minimum text length in UITextField before enabling keyboard return key

开发者 https://www.devze.com 2023-04-03 08:22 出处:网络
In my app users register or login at a site that requires passwords at least 6 characters long. To work with that I\'d like to impose that minimum in the password UITextField before the keyboard retur

In my app users register or login at a site that requires passwords at least 6 characters long. To work with that I'd like to impose that minimum in the password UITextField before the keyboard return button is enabled. Setting Auto-enable Return Key in the XIB causes the return key to be disabled until there is at least one character & (contrary to my expectations) turning that off causes the return key to be anabled even with no text.

开发者_高级运维Can anyone tell me how I can keep the return key disabled until the user has input 6 characters?


There is no apparent way to disable the return key until the user has entered 6 password characters. However, I have some other solutions for you that might serve the purpose.

  1. Writing a small message below the password field -- "Must be at least 6 characters"
  2. Showing alert when the password textfield loses focus.
-(void)textFieldDidEndEditing:(UITextField *)textField 
 {
   if([password length] <6)
      Show alert. On alert dismiss code block do this -->[password becomeFirstResponder]
 // this takes the focus back to the password field after alert dismiss.
 }
  1. Showing alert when the user presses return key.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([password length] <6)
    show alert like above.
}


The correct way to do this is with textFieldShouldEndEditing: and not textFieldDidEndEditing:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    BOOL shouldEnd = YES;

    if ([[textField text] length] < MINIMUM_LENGTH) {  
        shouldEnd = NO;
    }   

    return shouldEnd;
}


In Swift 3

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method

textField.resignFirstResponder()
   if let txt = textField.text as? String {
      if(txt.length >= minimum){
         textField.endEditing(true)
      }
   }  
   return false 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消