[英]Hide keyboard automatically in swift
輸入四個字符后,有沒有辦法在swift中自動隱藏鍵盤? 我實際上有一個隱藏鍵盤的代碼,但用戶必須單擊屏幕上的任意位置。 這是代碼:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
提前致謝!
如果我正確回答了您的問題,請考慮以下示例代碼:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var txtF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
txtF.delegate = self
txtF.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
func textFieldDidChange(textField: UITextField) {
if textField == txtF {
if textField.text?.characters.count == 4 {
self.txtF.resignFirstResponder()
}
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == txtF {
if textField.text?.characters.count > 3 {
self.txtF.resignFirstResponder()
return false
} else {
return true
}
} else {
return true
}
}
}
使用上面的代碼,當 textField 有 4 個字符時鍵盤將隱藏,之后如果用戶再次點擊 textField 鍵盤將彈出用戶將無法在 textField 中輸入任何文本並且鍵盤將再次隱藏。
結果將是:
希望這會有所幫助。
這是隱藏鍵盤或數字鍵盤的最簡單方法。 首先你需要一個按鈕,你需要讓它和屏幕一樣大。把它發送到場景的后面,並把它連接到一個 IBAction。然后你的代碼應該是這樣的:
@IBAction func HideKeyboard(sender: AnyObject) {
YourKeyboardHere.resignFirstResponder()
}
這應該適用於所有類型的鍵盤。
這對我有用:
// Outlet to textfield, editing changed
@IBAction func textFieldEditingChanged(sender: UITextField) {
if sender.text?.characters.count == 4 {
view.endEditing(true)
}
// Optional if you don't want the user to paste in more than 4 characters
else if sender.text?.characters.count > 4 {
sender.text = nil
}
}
我還建議您設置
textField.clearsOnBeginEditing = true
所以當用戶再次點擊 textField 時,它會被清除。
您應該使用文本字段委托shouldChangeCharactersInRange
類的,
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField.text.length == 4) {
[textField resignFirstResponder];
}
return YES;
}
在斯威夫特,
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField.text?.characters.count == 4 {
textField.resignFirstResponder()
}
return true
}
希望這會有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.