Swift--简单的定时器

定时器运用的场景也很多,譬如轮播图的自动滚动效果、注册时的发送短信按钮、自定义的定时动画效果等等。所以随手写写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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值