Textfield与计时器一起改变

时间:2017-02-27 18:26:55

标签: swift api autocomplete uitextfield

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

我希望它足够清楚 谢谢你的帮助!

2 个答案:

答案 0 :(得分:5)

在Swift 3中,你可能想要连接到“编辑已更改”而不是“值已更改”,并重置计时器并启动另一个计时器:

weak var timer: Timer?

@IBAction func didChangeEditing(_ sender: UITextField) {
    timer?.invalidate()
    timer = .scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] timer in
        // trigger your autocomplete
    }
}

或者您可以选择加入shouldChangeCharactersIn。例如:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self     // or you can do this in IB
    }

    weak var timer: Timer?

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        timer?.invalidate()           // cancel prior timer, if any

        timer = .scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] timer in
            // trigger your autocomplete
        }

        return true
    }
}

答案 1 :(得分:2)

首先确保将您的课程设为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()
    }
}

希望它有所帮助!