Last active
June 4, 2017 10:01
-
-
Save erica/6aa999a22803932c01a1d43274bf7444 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
retain cycle in resume?