当计时器结束时如何自动继续?

2024-01-09

我想在计时器用完时自动继续。

我在这里构建了一个计时器:

class Timer{
var timer = NSTimer();
// the callback to be invoked everytime the timer 'ticks'
var handler: (Int) -> ();
//the total duration in seconds for which the timer should run to be set by the caller
let duration: Int;
//the amount of time in seconds elapsed so far
var elapsedTime: Int = 0;
var targetController = WaitingRoomController.self


/**
:param: an integer duration specifying the total time in seconds for which the timer should run repeatedly
:param: handler is reference to a function that takes an Integer argument representing the elapsed time allowing the implementor to process elapsed time and returns void
*/
init(duration: Int , handler : (Int) -> ()){
    self.duration = duration;
    self.handler = handler;
}

/**
Schedule the Timer to run every 1 second and invoke a callback method specified by 'selector' in repeating mode
*/
func start(){
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onTick", userInfo: nil, repeats: true);
}

/**
invalidate the timer
*/
func stop(){
    println("timer was invaidated from stop()")
    timer.invalidate();
}


/**
Called everytime the timer 'ticks'. Keep track of the total time elapsed and trigger the handler to notify the implementors of the current 'tick'. If the amount of time elapsed is the same as the total duration for the timer was intended to run, stop the timer.
*/


@objc func onTick() {
    //println("onTick")
    //increment the elapsed time by 1 second
    self.elapsedTime++;
    //Notify the implementors of the updated value of elapsed time
    self.handler(elapsedTime);
    //If the amount of elapsed time in seconds is same as the total time in seconds for which this timer was intended to run, stop the timer
    if self.elapsedTime == self.duration {
        self.stop();

    }
}
deinit{
    println("timer was invalidated from deinit()")
    self.timer.invalidate();
}

}

这是我想要执行 segue 的视图控制器以及计时器如何启动:

class WaitingRoomController: UIViewController {

    private func handleSetAction(someTime: String){
       countDownLabel.text = setTime;
       let duration = Utils.getTotalDurationInSeconds(someTime);
       timer = Timer(duration: duration ){
          (elapsedTime: Int) -> () in
             println("handler called")
            let difference = duration - elapsedTime;
            self.countDownLabel.text = Utils.getDurationInMinutesAndSeconds(difference)
       }
       timer.start();
    }
}

我知道自动转换的代码是:

func doSegue(){
    self.performSegueWithIdentifier("asdf", sender: self)
}

但我不知道如何将计时器和这个功能连接在一起。


你需要使用闭包来实现你想要的,看看我的课Timer.

import UIKit

class Timer: NSObject {

    var counter: Int = 0
    var timer: NSTimer! = NSTimer()

    var timerEndedCallback: (() -> Void)!
    var timerInProgressCallback: ((elapsedTime: Int) -> Void)!

    func startTimer(duration: Int, timerEnded: () -> Void, timerInProgress: ((elapsedTime: Int) -> Void)!) {

       if !(self.timer?.valid != nil) {
           let aSelector : Selector = "updateTime:"

           timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: duration, repeats: true)

           timerEndedCallback = timerEnded
           timerInProgressCallback = timerInProgress
           counter = 0
       }
    }

    func updateTime(timer: NSTimer) {

       ++self.counter
       let duration = timer.userInfo as! Int

       if (self.counter != duration) {
          timerInProgressCallback(elapsedTime: self.counter)
       } else {
          timer.invalidate()
          timerEndedCallback()
       }
    }
}

然后你可以调用Timer通过以下方式进行类:

var timer = Timer()

timer.startTimer(5, timerEnded: { () -> Void in
        // Here you call anything you want when the timer finish.
        println("Finished")

        }, timerInProgress: { (elapsedTime) -> Void in
            println("\(Int(elapsedTime))")
})

上面的类在计时器已经有效时处理计时器的使用,并注意duration参数被传递给updateTime处理程序使用userInfo in the timer范围。

我希望这对你有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当计时器结束时如何自动继续? 的相关文章

随机推荐

  • 为什么 argc 是“int”(而不是“unsigned int”)?

    为什么命令行参数计数变量 传统上argc an int而不是unsigned int 这有技术原因吗 当我试图摆脱所有已签名的未签名比较警告时 我总是忽略它 但从来不明白为什么它是这样的 事实上 最初的 C 语言是这样的 默认任何变量或参数
  • OpenOPC Gateway 在 OsX 或 Linux 中运行使用客户端

    我用OpenOPC图书馆python https sourceforge net projects openopc https sourceforge net projects openopc 在网关模式 网关在 Windows 上运行 客
  • 在事务中执行多个语句之前准备它们?

    在执行之前准备多个语句可以吗 db PDO connection info cats stmt db gt prepare SELECT FROM cats dogs stmt db gt prepare SELECT FROM dogs
  • Microsoft.AspNetCore.Mvc.Controller 中的 ActionContext 消失了

    我在 Microsoft AspNetCore Mvc Controller 中找不到 ActionContext 当我将版本更改为 AspNetCore 1 0 0 preview1 后 这是控制器类 更改后 并从 微软 AspNet M
  • 如何配置 Spring Boot Kafka 客户端使其不尝试连接

    这与Spring Boot Kafka 客户端有 断路器 吗 https stackoverflow com q 69914621 2886891 但我仍然认为这是一个不同的问题 我们需要配置 Spring Boot Kafka 客户端 以
  • Java中JSONPath的基本使用

    我有 JSON 作为字符串和 JSONPath 作为字符串 我想使用 JSON 路径查询 JSON 以字符串形式获取结果 JSON 我认为Jayway 的 json path https code google com p json pat
  • Javascript 原型链接超类构造函数和方法调用

    我是 JavaScript 世界的新手 当我尝试原型链继承时 我遇到了这个奇怪的问题 我有3节课 class parent function parent param 1 this param param 1 this getObjWith
  • 使用 Emacs 作为 IDE

    目前 当我使用 C 或 C 进行编码时 我使用 Emacs 的工作流程涉及三个窗口 右侧最大的包含我正在使用的文件 左侧分为两部分 底部是一个 shell 我用它来输入编译或 make 命令 顶部通常是我在工作时想要查阅的某种文档或自述文件
  • 如何将字符串转换为 const class int 值?

    我有变量 String colorName BLUE 我想在 Android 应用程序中将此颜色设置为油漆 它应该是这样的 paint setColor Color colorName 但我收到错误警告 因为 setColor 函数的参数应
  • Spring RestTemplate,在解析为 Json 之前拦截响应

    我有一个 REST api 它在正文内容中响应一些额外的非 JSON 数据 这破坏了 RestTemplate 和 jackson 的使用 我可以在解析之前拦截http响应正文吗 我正在使用 RestTemplate getForObjec
  • 如何将不以特定模式开头的行连接到 UNIX 中的上一行?

    请查看下面的示例文件和所需的输出 以了解我正在寻找的内容 它可以通过 shell 脚本中的循环来完成 但我正在努力获得一个awk sed一艘班轮 示例文件 txt These are leaves These are branches Th
  • std::vector 向下调整大小

    C 标准似乎没有声明任何有关容量的副作用resize n with n lt size or clear 它确实对摊余成本做出了声明push back and pop back O 1 我可以设想一种执行通常类型的容量更改的实现 ala C
  • iPhone 应用程序启动

    如何让我的 iPhone 应用程序每次都在同一位置启动 即我的 主 屏幕 我不希望用户回到上次玩游戏时的位置 就在游戏过程中 但这就是正在发生的事情 预先感谢您的任何提示 您需要设置UIApplicationExitsOnSuspend输入
  • asp-for 和 if 条件在同一组件中

    我正在尝试在组件内使用 asp for 和条件 但我找不到方法来做到这一点 这是我的代码
  • 设置定时器问题

    我的双核机器上运行以下代码 当我在同一台 PC 上运行该应用程序的一两个实例时 我的正确计时分辨率为 100 毫秒 然而 当我在同一台 PC 上运行同一应用程序的 3 个实例时 计时分辨率超过 100 毫秒 是否有可能使应用程序的 3 个实
  • Magento XML 用简单的英语构建?

    我一直在阅读有关 Magento 的内容 并且了解其请求周期的核心流程等 基于配置的 MVC 和类重写等 但是 我似乎找不到关于具体细节的好文章 文档 特别是当涉及到为自定义模块等构建 config xml 所需的不同节点时 或者 XML
  • 将不同版本的 python 与 virtualenvwrapper 一起使用

    我使用 Macports 在我的 Mac 上安装了各种版本的 python 当我选择 python 2 7 通过 port select python python27 virtualenvwrapper 工作完美 但是如果我选择另一个版本
  • 使用 boost 创建具有自定义环境的子进程

    文档boost https www boost org doc libs 1 64 0 doc html process html没有提供任何使用自定义环境创建子进程的示例process child 给出了一个例子process syste
  • 如何在单个事务中保存多个 django 模型?

    在我看来 我将数据保存在多个模型中 def myview request do some processing model1 save model2 save 如何确保有回滚model1 save 以防万一model2 save 引发错误
  • 当计时器结束时如何自动继续?

    我想在计时器用完时自动继续 我在这里构建了一个计时器 class Timer var timer NSTimer the callback to be invoked everytime the timer ticks var handle