微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – Textfield确实改变了计时器

我正在我的项目中进行自动完成,我想检测textfieldDidChange值的时间并在此之后调用一个方法(链接到API)500MS.

我希望它足够清楚
谢谢您帮忙 !

解决方法

首先确保使您的类成为TextField的委托:

class yourClass: UIViewController,UITextFieldDelegate{
    //...
}

然后在viewDidLoad()中:

textField.delegate = self
numbersTextField.addTarget(self,action: #selector(self.textFieldDidChange),for: .editingChanged)

之后,您可以使用计时器,如下所示:

var timer = Timer()
var count = 0

func textFieldDidChange(textField: UITextField){
     timer.invalidate()
     timer = Timer.scheduledTimer(timeInterval: 0.1,target: self,selector: #selector(self.timerFunc),userInfo: nil,repeats: true)
}

func timerFunc(){
    count += 1
    if count == 5{
        timer.invalidate()
        // do your things here down here,I assumed that your method is called autocomplete
        autocomplete()
    }
}

希望能帮助到你!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐