Skip to content

Instantly share code, notes, and snippets.

@erica
Last active June 4, 2017 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/6aa999a22803932c01a1d43274bf7444 to your computer and use it in GitHub Desktop.
Save erica/6aa999a22803932c01a1d43274bf7444 to your computer and use it in GitHub Desktop.
import UIKit
import PlaygroundSupport
@objc class ViewController: UIViewController {
public func bbi(_ title: String, _ action: Selector) -> UIBarButtonItem {
return UIBarButtonItem(title: title, style: .plain, target: self, action: action)
}
var timer: Timer? = nil
var timeRemaining: Double = 0
func reset(_ item: UIBarButtonItem?) {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = bbi("Start", #selector(start(_:)))
timer?.invalidate(); timer = nil
timeRemaining = 0
title = ""
}
func pause(_ item: UIBarButtonItem?) {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = bbi("Resume", #selector(resume(_:)))
timer?.invalidate(); timer = nil
}
func tick() {
guard timeRemaining > 0 else {
reset(nil); return
}
title = "Time remaining: \(timeRemaining)"
timeRemaining -= 1.0
}
func resume(_ item: UIBarButtonItem?) {
navigationItem.rightBarButtonItem = bbi("Pause", #selector(pause(_:)))
navigationItem.leftBarButtonItem = bbi("Reset", #selector(reset(_:)))
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { _ in self.tick() } )
tick()
}
func start(_ item: UIBarButtonItem?) {
timeRemaining = 10.0
resume(nil)
}
public override func viewDidLoad() {
super.viewDidLoad()
tick()
}
}
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
PlaygroundPage.current.liveView = nav
PlaygroundPage.current.needsIndefiniteExecution = true
@seanwoodward
Copy link

retain cycle in resume?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment