在自定义 UITextField 上关闭键盘
Dismissing Keyboard on Custom UITextField
我正在使用 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)
}
你有什么建议吗?
为您的 textField 设置委托,也许它会起作用!
class ViewController: UIViewController, UITextFieldDelegate //add this protocol
{
...
func ... {
let textField = HoshiTextField(frame: textFieldFrame)
textField.placeholderColor = .darkGrayColor()
textField.foregroundColor = .lightGrayColor()
textField.delegate = self
}
}
确认 UITextFieldDelegate 协议到您的 ViewController 并分配 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)
}
为了更好地理解请看我的代码片段
我正在使用 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)
}
你有什么建议吗?
为您的 textField 设置委托,也许它会起作用!
class ViewController: UIViewController, UITextFieldDelegate //add this protocol
{
...
func ... {
let textField = HoshiTextField(frame: textFieldFrame)
textField.placeholderColor = .darkGrayColor()
textField.foregroundColor = .lightGrayColor()
textField.delegate = self
}
}
确认 UITextFieldDelegate 协议到您的 ViewController 并分配 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)
}
为了更好地理解请看我的代码片段