iOS筆記: 虛擬鍵盤part. 1 – 隱藏虛擬鍵盤

當我們在進行iOS的使用者界面設計時,經常會用到Text Field來讓使用者進行輸入的功能,當輸入焦點進入Text Field時,系統會自動的帶出虛擬鍵盤來讓使用者輸入,但是當使用者輸入完成時,虛擬鍵盤並不會自動隱藏,這個部分必需要由開發者在程式碼中去定義虛擬鍵盤需要隱藏的時機。


本文重點
– 按下鍵盤上的完成後隱藏虛擬鍵盤
– 使用手勢操作來隱藏虛擬鍵盤

Xcode專案

建立新專案

iOS → Application → Single View Application

enter image description here

UI Layout

在頁面上方,放置一個 Text Field
並建立delegate連結

enter image description here

按下鍵盤上的「完成」後隱藏虛擬鍵盤

ViewController.swift 加入以下程式碼

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

執行

enter image description here

使用手勢操作來隱藏虛擬鍵盤

ViewController.swift 加入以下程式碼

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

執行

enter image description here

範例程式碼

GitHub

延伸閱讀: iOS筆記: 虛擬鍵盤part. 2 – 不讓鍵盤阻擋文字方塊

發表留言