Guest User

Untitled

a guest
May 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. //: A UIKit based Playground for presenting user interface
  2.  
  3. import UIKit
  4. import PlaygroundSupport
  5.  
  6. class MyViewController : UIViewController {
  7.  
  8. // Timer to record the length of time between debounced calls
  9. var timer: Timer? = nil
  10.  
  11. override func loadView() {
  12. super.loadView()
  13.  
  14. let view = UIView()
  15. view.backgroundColor = .white
  16.  
  17. // Set up the slider
  18. let slider = UISlider(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
  19. slider.minimumValue = 0
  20. slider.maximumValue = 100
  21. slider.isContinuous = true
  22. slider.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
  23. self.view.addSubview(slider)
  24. }
  25.  
  26. @objc func sliderValueDidChange(_ sender: UISlider) {
  27. // Coalesce the calls until the slider valude has not changed for 0.2 seconds
  28. debounce(seconds: 0.2) {
  29. print("slider value: (sender.value)")
  30. }
  31. }
  32.  
  33. // Debounce function taking a time interval to wait before firing after user input has stopped
  34. // and a function to execute when debounce has stopped being called for a period of time.
  35. func debounce(seconds: TimeInterval, function: @escaping () -> Swift.Void ) {
  36. timer?.invalidate()
  37. timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in
  38. function()
  39. })
  40. }
  41. }
  42.  
  43. // Present the view controller in the Live View window
  44. PlaygroundPage.current.liveView = MyViewController()
  45. PlaygroundPage.current.needsIndefiniteExecution = true
  46.  
  47. func debounce(seconds: TimeInterval, function: @escaping () -> Swift.Void ) {
  48. timer?.invalidate()
  49. timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { _ in
  50. function()
  51. })
  52. }
Add Comment
Please, Sign In to add comment