Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: A UIKit based Playground for presenting user interface
- import UIKit
- import PlaygroundSupport
- class MyViewController : UIViewController {
- // Timer to record the length of time between debounced calls
- var timer: Timer? = nil
- override func loadView() {
- super.loadView()
- let view = UIView()
- view.backgroundColor = .white
- // Set up the slider
- let slider = UISlider(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
- slider.minimumValue = 0
- slider.maximumValue = 100
- slider.isContinuous = true
- slider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
- self.view.addSubview(slider)
- }
- @objc func sliderValueDidChange(_ sender: UISlider) {
- // Coalesce the calls until the slider valude has not changed for 0.2 seconds
- debounce(seconds: 0.2) {
- print("slider value: (sender.value)")
- }
- }
- // Debounce function taking a time interval to wait before firing after user input has stopped
- // and a function to execute when debounce has stopped being called for a period of time.
- func debounce(seconds: TimeInterval, function: @escaping () -> Swift.Void ) {
- timer?.invalidate()
- timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in
- function()
- })
- }
- }
- // Present the view controller in the Live View window
- PlaygroundPage.current.liveView = MyViewController()
- PlaygroundPage.current.needsIndefiniteExecution = true
- func debounce(seconds: TimeInterval, function: @escaping () -> Swift.Void ) {
- timer?.invalidate()
- timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in
- function()
- })
- }
Add Comment
Please, Sign In to add comment