iT邦幫忙

0

iOS SDK 學習筆記01:UIResponder & Delegate design pattern — 以收起鍵盤為例

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20230404/20158406MdLdqxNvQc.jpg

本文是我在 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 裡。
而要實現隱藏鍵盤,需要以下步驟:

  1. 在你要實現的 ViewController 中 conform UITextFieldDelegate 這個協定。

  2. 定義 textFieldShouldReturn(_:)

    extension ViewController: UITextFieldDelegate {
      func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
      }
    
  3. 函式裡面需要呼叫 resignFirstResponder() 這個函式,用意是請求該 textField 放棄其 first responder 的地位。而依據 Apple 官方文件,最後需要 return true。


這邊一開始比較不好理解的是 Delegate Design Pattern。在 iOS 開發中,Delegate Design Pattern 很常用於控制使用者介面的一些行為,例如當使用者點擊一個按鈕或輸入文字時,需要執行什麼樣的操作等。
UITextFieldDelegate 就是一個代理協議,它定義了一些方法,例如這邊的 textFieldShouldReturn() 等。當使用者點擊一個 UITextField 時,系統會自動調用相應的代理方法,以執行一些操作(例如讓鍵盤彈出等)。

// UITextField
class UITextField {
    var delegate: UITextFieldDelegate
    // some codes
    delegate.textFieldShouldReturn()
}
// Another Class
class AnotherClass {
    let textField = UITextField()
    textField.delegate = self
}

因為 Apple 官方並沒有開源 UITextField 背後到底是如何實作的,因此只能大概推論背後的實作模式是這樣(如果有錯還請指正)。
透過採用 UITextFieldDelegate 這個協議,以及利用 textField.delegate = self 將 Class 自己指派給 delegate,就不用在 UITextField 裡事先定義每一個調用 textFieldShouldReturn() 這個方法的 Class 有哪些。這樣一來,我們就可以很方便地在 UITextField 的 delegate 方法中進行一些自定義的操作,而不需要修改 UITextField 這個 Class 的程式碼。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言