Xcode
Swift
swift4

コードだけでシンプルなタイマーアプリを作る

はじめに

前回書いたこちらを応用して、簡単なタイマーアプリを作ってみました。

完成形

image.png

実装

AppDelegate.swift

前回とほとんど変わりません。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.white
        self.window?.rootViewController = ViewController()
        self.window?.makeKeyAndVisible()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

ViewController.swift

タイマーの機能を追加しています。

import UIKit

class ViewController: UIViewController {

    let label = UILabel()
    var count: Int = 0
    let startBtn = UIButton()
    let stopBtn = UIButton()
    let resetBtn = UIButton()
    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let viewWidth = self.view.bounds.width
        let viewHeight = self.view.bounds.height

        label.frame = CGRect(x: viewWidth / 4, y: viewHeight / 2 - 50, width: viewWidth / 2, height: 30)
        label.text = "0"
        label.font = UIFont.systemFont(ofSize: 30)
        label.textAlignment = .center
        self.view.addSubview(label)

        startBtn.frame = CGRect(x: viewWidth - 170, y: viewHeight / 2, width: 150, height: 150)
        startBtn.setTitle("Start", for: .normal)
        startBtn.backgroundColor = UIColor.blue
        startBtn.setTitleColor(UIColor.white, for: .normal)
        startBtn.layer.cornerRadius = 75.0
        startBtn.addTarget(self, action: #selector(self.start), for: .touchUpInside)
        self.view.addSubview(startBtn)

        stopBtn.frame = CGRect(x: 20, y: viewHeight / 2, width: 150, height: 150)
        stopBtn.setTitle("Stop", for: .normal)
        stopBtn.backgroundColor = UIColor.red
        stopBtn.setTitleColor(UIColor.white, for: .normal)
        stopBtn.layer.cornerRadius = 75.0
        stopBtn.addTarget(self, action: #selector(self.stop), for: .touchUpInside)
        self.view.addSubview(stopBtn)

        resetBtn.frame = CGRect(x: viewWidth / 4, y: viewHeight / 2 + 180, width: viewWidth / 2, height: 40)
        resetBtn.setTitle("RESET", for: .normal)
        resetBtn.setTitleColor(UIColor.white, for: .normal)
        resetBtn.backgroundColor = UIColor.black
        resetBtn.addTarget(self, action: #selector(self.reset), for: .touchUpInside)
        self.view.addSubview(resetBtn)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @objc func start(){
        if timer.isValid == true {
            return
        }

        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
    }

    @objc func stop(){
        timer.invalidate()
    }

    @objc func reset(){
        timer.invalidate()
        count = 0
        label.text = String(count)
    }

    @objc func updateTime(){
        count += 1
        label.text = String(count)
    }

}

コードベースのみでMVCで構築する手順をどう学ぼうか考え中ですので、アドバイス等ありましたら、コメントいただけますと幸いですm(_ _)m