在自定义UITextField上关闭键盘

时间:2016-03-15 01:29:51

标签: ios swift keyboard uitextfield uikeyboard

我正在使用TextFieldEffects来定制UITextFields。创建文本域非常简单..

class ViewController: UIViewController {

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

        view.addSubView(textField) 
   }
}

为了解雇键盘,我试着做我通常做的事情,但遗憾的是没有运气。

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

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

你有什么建议吗?

3 个答案:

答案 0 :(得分:2)

确认ViewController的UITextFieldDelegate协议并指定textField.delegate = self,然后实现以下委托方法:

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

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

为了更好地理解,请参阅我的代码snipet enter image description here

答案 1 :(得分:1)

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

答案 2 :(得分:0)

为你的textField设置委托,也许它会起作用!