輸入四個字符後能快速自動隱藏鍵盤嗎?我其實有一個隱藏鍵盤的代碼,但用戶必須點擊屏幕上的任何位置。這裏的代碼:快速自動隱藏鍵盤
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
在此先感謝!
輸入四個字符後能快速自動隱藏鍵盤嗎?我其實有一個隱藏鍵盤的代碼,但用戶必須點擊屏幕上的任何位置。這裏的代碼:快速自動隱藏鍵盤
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
在此先感謝!
您應該使用文本框代表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
}
希望這將有助於:)
這爲我工作:
// 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在用戶再次點擊它時被清除。
如果我正確地得到了你的問題,考慮下面的示例代碼:
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
}
}
}
有了上面的代碼鍵盤時,文本字段有4個字符將隱藏後,如果用戶再次文本框鍵盤上點擊會彈出是用戶不能夠輸入任何文本到textField和鍵盤將再次隱藏。
結果將是:
希望這會有所幫助。
這裏是隱藏鍵盤或數字鍵盤最簡單的方法。 首先你需要一個按鈕,你需要使它的screen.Send它的大小到現場的背面,其連接到IBAction.Then你的代碼應該是這樣的:
@IBAction func HideKeyboard(sender: AnyObject) {
YourKeyboardHere.resignFirstResponder()
}
這應該適用於所有類型的鍵盤。
請參閱http://stackoverflow.com/questions/28394933/how-do-i-check-when-a-uitextfield-changes讓方法檢查當前長度。如果尺寸合適,請關閉鍵盤。 – rmaddy
可能重複[如何隱藏快捷鍵按下回車鍵?](http://stackoverflow.com/questions/24180954/how-to-hide-keyboard-in-swift-on-pressing-return-key) –
@AbhinandanPratap不,這不是重複的,因爲OP在按下返回鍵時不會詢問如何關閉鍵盤。 – rmaddy