在 iOS 開發中,UITextField 獲得焦點時會自動彈出鍵盤,但如何在使用者完成輸入後「收起」鍵盤,是初學者常遇到的問題。本文以 Swift 為例,總結兩種常見的關閉鍵盤方式。
首先是基本的介面搭建:創建一個 UITextField,設置邊框顏色與線寬,並將其 delegate 指向當前控制器,同時讓控制器遵循 UITextFieldDelegate 協議。
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var textF = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
self.addUITextField()
}
func addUITextField() {
let text: UITextField = UITextField(frame: CGRectMake(30, 100, 260, 30))
text.layer.borderColor = UIColor.lightGrayColor().CGColor
text.layer.borderWidth = 2
self.view.addSubview(text)
text.delegate = self
self.textF = text
}
}
重寫 touchesBegan 方法,當使用者點擊畫面時,讓 textField 結束第一響應者的身份,鍵盤便會隨之收起:
// override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// self.textF.resignFirstResponder()
// }
實現 UITextFieldDelegate 的 textFieldShouldReturn 方法。當使用者按下鍵盤上的「完成/回車」鍵時,觸發該方法,調用 resignFirstResponder() 即可讓鍵盤消失:
func textFieldShouldReturn(textField: UITextField) -> Bool {
if self.textF == textField {
textField.resignFirstResponder()
}
return true
}
總結一下:方法一適合「點擊空白處收起鍵盤」的交互場景,方法二則對應「按回車鍵收起鍵盤」。兩者可以結合使用,為使用者提供更加自然順暢的輸入體驗。核心關鍵在於 resignFirstResponder()——讓 textField 放棄第一響應者身份,鍵盤自然便會收回。