开发者

Change UITextField behavior

开发者 https://www.devze.com 2023-04-04 22:28 出处:网络
What is the best way to disable UITextField\'s \'return\' keyboard key if input area does not contain any text? UITextField with enablesReturnKeyAutomatically property set to YES enables return key ev

What is the best way to disable UITextField's 'return' keyboard key if input area does not contain any text? UITextField with enablesReturnKeyAutomatically property set to YES enables return key even if there are only spaces entered, but I'd like it to ena开发者_如何学编程ble return key only when the text is not empty. any suggestions?


I don't know how you'd override the text input trait behaviour, but you could use the text field delegate method textField:shouldChangeCharactersInRange:replacementString: to prevent the user being able to enter spaces into an otherwise blank string. This would prevent any whitespace text being added, so the return key should not be enabled.

If you're not bothered about the return key actually being enabled, you could use textFieldShouldReturn:, again one of the text field delegate methods.


I would do something like the following

  1. Create an extension to String and add a trim method (it will become handy in other scenarios too that's why I suggest an extension.

    public func trim() -> String {
      return  stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    }
    
  2. Make your class a delegate of UITextFieldDelegate and add the following fuction

    func textFieldDidChange(textField: UITextField) {
      textField.text = textField.text.trim()
    }
    
  3. Set the delegate of your UITextField to self.

0

精彩评论

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