swift 關(guān)閉鍵盤的兩種方法

第一種:通過鍵盤內(nèi)的完成按鈕來實現(xiàn)關(guān)閉鍵盤
  首先繼承 UITextFieldDelegate
  以輸入框 textField舉例,執(zhí)行以下代碼

title_textField.delegate = self
title_textField.returnKeyType = UIReturnKeyType.done
    鍵盤輸入時會出現(xiàn)完成按鈕,如圖
99459FD3-206A-4B6C-841D-A21E9F503516.png
    執(zhí)行以下方法便可觸發(fā)點擊完成的事件
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        title_textField.resignFirstResponder()
        return true
}

第二種:在鍵盤上方加一個 UIToolbar,觸發(fā) UIToolbar事件執(zhí)行關(guān)閉
效果如圖,右上角


94A0058D-1576-40E0-A7B1-50F8F422AE47.png

定義UIToolbar

let toolbar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0,  width: self.view.frame.size.width, height: 30))
let flexSpace = UIBarButtonItem(barButtonSystemItem:    .flexibleSpace, target: nil, action: nil)
let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(doneButtonAction))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
 
//對輸入框進行設置
title_textField.inputAccessoryView = toolbar

觸發(fā)事件

func doneButtonAction() {
        title_textField.resignFirstResponder()
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容