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

陌路散爱 提交于 2019-12-10 20:27:41

问题


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?


回答1:


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.
}



回答2:


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;
}



回答3:


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 
}


来源:https://stackoverflow.com/questions/7329631/how-to-require-a-minimum-text-length-in-uitextfield-before-enabling-keyboard-ret

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!