问题描述
我已经挖掘了stackoverflow并找到了我转换为Swift的解决方案,它似乎不起作用且选择器仍在执行。
I've dug around stackoverflow and found the solution which I converted to Swift, it doesn't seem to work and the selector is still being performed.
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.filter.searchTerm = self.searchBar.text
NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "getHints", object: nil)
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "getHints", userInfo: nil, repeats: false)
}
有没有更好的方法在swift中执行此操作?
谢谢!
Is there a better way to do this in swift?Thanks!
推荐答案
更新2016/09/01:
我们可以使用 NSTimers
或(自swift 2.0起)NSObject的 performSelector
和朋友。
We can use NSTimers
or (since swift 2.0) NSObject's performSelector
and friends.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
NSObject.cancelPreviousPerformRequests(
withTarget: self,
selector: #selector(ViewController.getHintsFromTextField),
object: textField)
self.perform(
#selector(ViewController.getHintsFromTextField),
with: textField,
afterDelay: 0.5)
return true
}
func getHintsFromTextField(textField: UITextField) {
print("Hints for textField: \(textField)")
}
方法2: NSTimer
Approach 2: NSTimer
var timer: NSTimer? = nil
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
timer?.invalidate()
timer = Timer.scheduledTimer(
timeInterval: 0.5,
target: self,
selector: #selector(ViewController.getHints),
userInfo: ["textField": textField],
repeats: false)
return true
}
func getHints(timer: Timer) {
var userInfo = timer.userInfo as! [String: UITextField]
print("Hints for textField: \(userInfo["textField"])")
}
注意我将 textField
传递给延迟函数。它并不总是必需的,但当 textField
不易访问或处理各种文本字段时,它可以让您的生活更轻松。
Note I am passing the textField
to delayed functions. It is not always required but it could make your life easier when textField
is not easy to access or when dealing with various text fields.
当您致电 performSelector
时,目标 保留(在swift中,目标总是 self
)但是当你使用 NSTimer
时,目标 不是 保留。这意味着,如果你使用 NSTimer
s,你必须确保目标(在这种情况下是 self
)是活着的计时器开火的时间。否则会发生崩溃。
When you call performSelector
the target is retained (in swift the target is always self
) but when you use NSTimer
the target is NOT retained. This means, if you use NSTimer
s, you have to make sure target (in this case self
) is alive by the time the timer fires. Otherwise the a crash will occur.
这篇关于检测用户何时在Swift中停止/暂停键入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!