简体   繁体   中英

Dismissing Keyboard on Custom UITextField

I am using TextFieldEffects for custom UITextFields. Creating the textfield was pretty straight forward..

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
        let textField = HoshiTextField(frame: textFieldFrame)
        textField.placeholderColor = .darkGrayColor()
        textField.foregroundColor = .lightGrayColor()

        view.addSubView(textField) 
   }
}

For dismissing the keyboard, I tried to do what I usually do, but unfortunately no luck.

func textFieldShouldReturn(textField: HoshiTextField) -> Bool {
    self.view.endEditing(true)
    return false
}

func dismissKeyboard() {
    view.endEditing(true)
}

Do you have any suggestions?

Confirm the UITextFieldDelegate protocol to your ViewController and assign textField.delegate = self and then implement the following delegate method:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
  }

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
  }

For better understanding please see my code snipet 在此处输入图片说明

class ViewController: UIViewController, UITextFieldDelegate //add this protocol 
{
...
  func ... {
    let textField = HoshiTextField(frame: textFieldFrame)
    textField.placeholderColor = .darkGrayColor()
    textField.foregroundColor = .lightGrayColor()
    textField.delegate = self
  }
}

为您的textField设置委托,也许它将起作用!

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