定时器运用的场景也很多,譬如轮播图的自动滚动效果、注册时的发送短信按钮、自定义的定时动画效果等等。所以随手写写swift的定时器,有需要的人可以参考参考,代码实现功能部分,UI部分使用拖拉控件的形式。文章尾部有Demo下载链接
//
// ViewController.swift
// swiftTimer
//
// Created by hhg on 16/7/21.
// Copyright © 2016年 hhg. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// 宽高 S = screen
let SWIDTH = UIScreen.mainScreen().bounds.size.width
// 属性 OC可以用0. swift只能用0.0
var counter = 0.0
var timer = NSTimer()
var isPlaying = false
// 计数器的屏幕、开始键、暂停键、重置键
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var pauseBtn: UIButton!
@IBOutlet weak var resetBtn: UIButton!
// 设置状态栏的颜色为白色
/*
状态栏黑色 UIStatusBarStyle.Default
状态栏白色 UIStatusBarStyle.LightContent
*/
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
// 加载视图
override func viewDidLoad() {
super.viewDidLoad()
// 创建
self.createLabel()
self.createBtn()
}
// 创建label
func createLabel() {
timeLabel.text = String(counter)
timeLabel.layer.cornerRadius = SWIDTH / 6.0
timeLabel.clipsToBounds = true
}
func createBtn() {
// 开始按钮
startBtn.addTarget(self, action: #selector(ViewController.play(_:)), forControlEvents: .TouchUpInside)
// 重置按钮
resetBtn.addTarget(self, action: #selector(ViewController.reset(_:)), forControlEvents: .TouchUpInside)
// 暂停按钮
pauseBtn.addTarget(self, action: #selector(ViewController.pasuse(_:)), forControlEvents: .TouchUpInside)
}
// 开始功能
func play(btn:UIButton) {
if isPlaying {
return
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true)
isPlaying = true
}
// 重置功能
func reset(btn:UIButton) {
timer.invalidate()
counter = 0
timeLabel.text = String(counter)
isPlaying = false
}
// 暂停功能
func pasuse(btn:UIButton) {
timer.invalidate()
isPlaying = false
}
// 定时功能
func updateTimer() {
counter = counter + 0.1
timeLabel.text = String(format: "%.1f",counter)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Demo下载链接 Demo