UITextField如何讓鍵盤消失?
Published in
3 min readAug 8, 2018
(UITextField, ScrollView)
一般點擊TextField後,鍵盤會從下方彈出。
但當編輯完成該如何讓鍵盤消失呢?
以下提供一般TextField跟使用scrollView讓鍵盤消失的方法。
單純的TextField
・點擊Return鍵
在Controller中新增 UITextFieldDelegate並將TextField的delegate 指向 Controller
同時透過textFieldShouldReturn定義按下return按鈕
・點擊空白處鍵盤消失
複寫 touchesBegan function
畫面會有這樣的效果
scrollView中TextField
請求輸入的項目多,但有些手機畫面較小,
透過ScrollView幫助畫面可以進行滑動,
但卻發現點擊其他地方收起鍵盤的功能無法使用,
原因在於Scroll View並沒有繼承touchesBegan。
・點擊Return鍵
方法與單純的TextField相同
・點擊空白處鍵盤消失
透過手勢(addGestureRecognizer)完成鍵盤消失的效果
參考資料:
ScrollView 原理
Swift: Keyboard behaviour. Why ‘touchesBegan’ not minimise keyboard when using scrollView?