在Swift中进行节流而无需做出反应

在Swift中进行节流而无需做出反应

本文介绍了在Swift中进行节流而无需做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在Reactive编程中实现Throttle功能,而不必使用RxSwift或类似框架.

Is there a simple way of implementing the Throttle feature in Reactive programming without having to use RxSwift or similar frameworks.

我有一个textField委托方法,我不想每次插入/删除字符时都将其触发.

I have a textField delegate method that I would like not to fire every time a character is inserted/deleted.

如何使用Vanilla Foundation做到这一点?

How to do that using vanilla Foundation?

推荐答案

是可以实现的.

但是首先让我们回答一个小问题:什么是节流?

But first lets answer small question what is Throttling?

Swift中调节函数的示例.

Example of the Throttling function in the Swift.

如果您使用委托方法进行描述,则会遇到每次调用该委托方法的问题.因此,我将写一个简短的示例,说明在您描述的情况下该怎么做.

In case that you have describe with delegate method you will have issue that delegate method will be called each time. So I will write short example how it impossible to do in the case you describe.

class ViewController: UIViewController {

    var timer: Timer?

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    @objc func validate() {
        print("Validate is called")
    }
}

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        timer?.invalidate()

        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.validate), userInfo: nil, repeats: false);

        return true
    }

}

这篇关于在Swift中进行节流而无需做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:22