gpt4 book ai didi

ios - 在 Swift 中 throttle 而不 react

转载 作者:可可西里 更新时间:2023-11-01 00:57:16 25 4
gpt4 key购买 nike

是否有一种无需使用 RxSwift 或类似框架即可在 Reactive 编程中实现 Throttle 功能的简单方法。

我有一个 textField 委托(delegate)方法,我不想在每次插入/删除字符时都触发它。

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

最佳答案

是的,这是可以实现的。

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

In software, a throttling process, or a throttling controller as it issometimes called, is a process responsible for regulating the rate atwhich application processing is conducted, either statically ordynamically.

Throttling 的示例Swift 中的函数。

如果您使用委托(delegate)方法进行描述,您将遇到每次都会调用委托(delegate)方法的问题。所以我会写一个简短的例子,说明在你描述的情况下是不可能做到的。

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
}

}

关于ios - 在 Swift 中 throttle 而不 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com