我应该如何检测 UITextField
中的输入是否停止?我应该使用某种 UITextFieldTextDidEndEditingNotification
函数吗?我试图创建一个类似搜索的 instagram,它会在一秒钟不输入后显示结果。
最佳答案
我就是这样做的,它适用于 Swift 3
import UIKit
// don't forget to add UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
var searchTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// declare textField as delegate
self.textField.delegate = self
// handle the editingChanged event by calling (textFieldDidEditingChanged(-:))
self.textField.addTarget(self, action: #selector(textFieldDidEditingChanged(_:)), for: .editingChanged)
}
// reset the searchTimer whenever the textField is editingChanged
func textFieldDidEditingChanged(_ textField: UITextField) {
// if a timer is already active, prevent it from firing
if searchTimer != nil {
searchTimer?.invalidate()
searchTimer = nil
}
// reschedule the search: in 1.0 second, call the searchForKeyword method on the new textfield content
searchTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(searchForKeyword(_:)), userInfo: textField.text!, repeats: false)
}
func searchForKeyword(_ timer: Timer) {
// retrieve the keyword from user info
let keyword = timer.userInfo!
print("Searching for keyword \(keyword)")
}
}
关于ios - 检测何时停止在 UITextField 中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227055/