本文是我在 iT 邦帮忙第一篇文章,这系列主要纪录学习 iOS SDK 的一些心得。
另外我的主要兴趣是摄影,想说可以在每一篇文章中偷渡自己的作品~
When the user taps a UITextField and UITextView object onscreen, the view becomes the first responder and displays its input view, which is the system keyboard.
在实作按下键盘上的 return 键时会隐藏键盘时会运用到 first responder 这个观念。
当使用者点击画面上某个 textField
时,会呼叫 becomeFirstResponder()
这个 method 使其变成 first responder。此时系统会自动跳出键盘,并将键盘输入的内容传到 textField
里。
而要实现隐藏键盘,需要以下步骤:
在你要实现的 ViewController 中 conform UITextFieldDelegate 这个协定。
定义 textFieldShouldReturn(_:)
extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true }
函式里面需要呼叫 resignFirstResponder() 这个函式,用意是请求该 textField 放弃其 first responder 的地位。而依据 Apple 官方文件,最后需要 return true。
这边一开始比较不好理解的是 Delegate Design Pattern。在 iOS 开发中,Delegate Design Pattern 很常用于控制使用者介面的一些行为,例如当使用者点击一个按钮或输入文字时,需要执行什么样的操作等。
UITextFieldDelegate 就是一个代理协议,它定义了一些方法,例如这边的 textFieldShouldReturn()
等。当使用者点击一个 UITextField 时,系统会自动调用相应的代理方法,以执行一些操作(例如让键盘弹出等)。
// UITextFieldclass UITextField { var delegate: UITextFieldDelegate // some codes delegate.textFieldShouldReturn()}
// Another Classclass AnotherClass { let textField = UITextField() textField.delegate = self}
因为 Apple 官方并没有开源 UITextField
背后到底是如何实作的,因此只能大概推论背后的实作模式是这样(如果有错还请指正)。
透过採用 UITextFieldDelegate
这个协议,以及利用 textField.delegate = self
将 Class 自己指派给 delegate,就不用在 UITextField
里事先定义每一个调用 textFieldShouldReturn()
这个方法的 Class 有哪些。这样一来,我们就可以很方便地在 UITextField
的 delegate 方法中进行一些自定义的操作,而不需要修改 UITextField
这个 Class 的程式码。