30天30swift项目挑战
笔者最近在学习swift,已经很迅速地把从零开始学Swift看了一遍,然后心想找点小项目来一面写一面加固Swift的基础,偶然间在github上看到#100 Days of Swift然后也想这样来充实一下自己。虽然把语法什么的都过了一遍,但是还是到了实战上面又会不一样,所以我就打算也开始每天写1~2个小项目来充实自己
项目挑战一:Stop Watch 计时器
项目展示
一、首先创建新项目
我们进行开发是使用xcode的
我门使用swift语言进行开发
完成后得到目录
二、打开Main.storyboard
分别设置背景颜色,新增label和3个按钮
三、创建SWViewController.swift
选择Cocoa Touch Class 然后点击next
然后Subclass选择UIViewController
四、代码部分
//
// SWViewController.swift
// Project01-StopWatch
//
// Created by space on 2018/4/20.
// Copyright © 2018年 space. All rights reserved.
//
import UIKit
import Foundation
class SWViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var playBtn : UIButton!
@IBOutlet weak var pauseBtn : UIButton!
var counter = 0.0
var timer = Timer()
var isPlaying = false
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
timeLabel.text = String(counter)
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/// 开始按钮
///
/// - Parameter sender: <#sender description#>
@IBAction func playButtonDidTouch(sender: AnyObject) {
if isPlaying {
return
}
playBtn.isEnabled = false
pauseBtn.isEnabled = true
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(SWViewController.updateTimer), userInfo: nil, repeats: true)
isPlaying = true
}
/// 暂停按钮
///
/// - Parameter sender: <#sender description#>
@IBAction func pauseButtonDidTouch(sender: AnyObject) {
playBtn.isEnabled = true
pauseBtn.isEnabled = false
timer.invalidate()
isPlaying = false
}
/// 重置按钮
///
/// - Parameter sender:
@IBAction func resetButtonDidTouch(sender: AnyObject){
timer.invalidate()
isPlaying = false
counter = 0.0
timeLabel.text = String(counter)
playBtn.isEnabled = true
pauseBtn.isEnabled = false
}
/// 更新timer
@objc func updateTimer(){
counter = counter + 0.1
timeLabel.text = String(format: "%.1f", counter)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
五、返回Main.storyboard
选择左边的View Controller Scene下的View Controller,右边Custom Class选择SWViewController (刚刚自己写的类)
选择这个
如图所示,将相关的按钮和outlets连接起来
最后就能运行程序了!!!!!