1、创建工程
创建工程<br />
2、布局UI
UI<br />
3、关联
关联<br />
4、添加方法
拖线到工程中5、开始做事:
1、点击开始按钮,开始计时,并显示的到label上,所以需要一个变量去存储。
2、点击停止按钮,停止计时。
//定义变量
var Time = 0.0;
var Timer = NSTimer()
开始按钮方法:
//点击开始
@IBAction func startClick(sender: UIButton) {
startBtn.enabled = false;
pauseBtn.enabled = true;
Timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.UpdateTimeLabel), userInfo: nil, repeats: true);
timeLabel.text = String(Time);
}
startBtn/pauseBtn.enable 设置当你点击开始了,就不允许点击开始,只能点击停止
Timer:创建一个定时器,当点击停止,把定时器停止
timeLabel:设置开始之前的值为0
点击停止按钮
//点击暂停
@IBAction func pauseClick(sender: UIButton) {
Timer.invalidate();
Time = 0.0
startBtn.enabled = true;
pauseBtn.enabled = false;
}
line 1 invalidate()关闭定时器
line 2 计数归零
line 3 4:设置停止按钮不能点击,只能点击开始按钮
更新label的方法:
//更新label
func UpdateTimeLabel() {
Time += 0.1;
timeLabel.text = String(format: "%.1f", Time)
}
line 1 累加
line 2 更新label
VC全部代码
//
// ViewController.swift
// Day_01计时器
//
// Created by ios on 16/9/5.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var pauseBtn: UIButton!
//定义变量
var Time = 0.0;
var Timer = NSTimer()
//设置状态栏style
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.Default
}
//view did load
override func viewDidLoad() {
super.viewDidLoad()
}
//收到内存警告
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//更新label
func UpdateTimeLabel() {
Time += 0.1;
timeLabel.text = String(format: "%.1f", Time)
}
//点击开始
@IBAction func startClick(sender: UIButton) {
startBtn.enabled = false;
pauseBtn.enabled = true;
Timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.UpdateTimeLabel), userInfo: nil, repeats: true);
timeLabel.text = String(Time);
}
//点击暂停
@IBAction func pauseClick(sender: UIButton) {
Timer.invalidate();
Time = 0.0
startBtn.enabled = true;
pauseBtn.enabled = false;
}
}
网友评论