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

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(使用前将#替换为@)

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

  • 我如何从子视图导航到 mainviewcontroller

    我刚刚开始使用 swift 我创建了一个子视图 上面有一个按钮 我想使用该按钮将我带到我的主视图控制器 我对不同的按钮使用了相同的功能 但是在同一文件中具有一个功能允许该按钮工作 代码如下 var playAgainButton UIBut
  • SwiftUI 列表与右侧的部分索引?

    是否可以有一个在右侧有索引的列表 就像下面 SwiftUI 中的示例一样 我在 SwiftUI 中做了这个 Contacts swift TestCalendar Created by Christopher Riner on 9 11 2
  • ios 用户如何取消 Facebook 登录?

    当用户到达此屏幕时 无法取消 我能做些什么 为了首先获得这个视图 我正在运行 NSMutableDictionary params NSMutableDictionary dictionaryWithObjectsAndKeys vid l
  • 使用 iOS 8 自定义键盘发送图像?

    我一直在为 iOS 8 开发自定义键盘 但在尝试使用键盘发送图像时偶然发现了一个问题 我做了一些研究 似乎没有一种简单的方法可以做到这一点UITextDocumentProxy因为只有NSStrings被允许 我是否忽略了使用自定义键盘发送
  • 将永久字符添加到 UITextField

    有没有办法将字母永久添加到 UITextField 中 用户无法删除它 我想添加一个字符 用户无法删除它 但他们仍然可以在之后添加字母 Cheers 附注这是适用于 iOS 的 A UITextField有一个名为 应该更改范围内的字符 的
  • 从 UIImagePickerController 相机视图推送 viewController

    我正在开发一款消息应用程序 类似于 WhatsApp 用户可以互相发送文本和图像消息 当用户想要发送图像时 他可以从相机胶卷中选择一张图像 也可以用相机拍摄一张图像 这就是我介绍的方式UIImagePickerController对于这两种
  • Swift Generics 在使用继承时不会实例化泛型

    我有课Alpha and Berry class Alpha class Berry Alpha 我有一个使用继承及其泛型的函数 func myFunc
  • UIButton 导致无法识别的选择器发送到实例

    我正在尝试使用 for 循环创建多个按钮 但在使用 sender 函数时遇到问题 我有以下代码 func setUpButtons for i in 1 3 let btn UIButton UIButton frame CGRect x
  • 如何打开定位服务

    当有人第一次拒绝时 如何从实际应用程序重新打开定位服务 我可以选择关闭或打开它 您只能提示他们在屏幕上打开定位服务 如下所示 UIApplication sharedApplication openURL NSURL URLWithStri
  • 在 Cocoa OS X AVPlayer 中播放 HLS (m3u8) - Swift

    基本上我正在尝试在 Cocoa Swift 中使用 AVPlayer 播放 m3u8 HLS Live Stream 我对这门语言比较陌生 所以基本上掌握了一些示例代码 http qiita com ono matope items 23d
  • 在横向中自动调整 UITableCells 内容的大小

    在 UITableView 中 我通过 UILabels 将内容添加到单元格中 定义最佳尺寸 与单元格宽度允许的一样大 我注意到只有tableView contentSize width是可靠的 因为cell contentView bou
  • 当地图视图只是屏幕的一部分时,如何在 iOS 模拟器中进行捏合?

    我在 iPad 上有一个视图 我正在添加MKMapView也就是说 全屏高度的一半 然而 当我尝试在 iOS 模拟器上进行捏合时 它不起作用 因为 to nubs 填充了模拟器上的整个 iPad 视图 And so with the map
  • 在 Swift 中从 UIScrollView 创建 PDF 文件

    我想从 UIScrollView 的内容创建一个 PDF 文件 func createPdfFromView aView UIView saveToDocumentsWithFileName fileName String let pdfD
  • 更改组织以使用 Xcode 9 在 iTunes Connect 上上传二进制文件

    我在 Xcode9 上配置了多个团队 当我尝试将二进制文件上传到 Xcode 9 上的 iTunes Connect 时 没有更改团队的选项 并且出现以下错误 ERROR ITMS 4088 来自苹果开发者论坛的解决方案 1 正常存档2 窗
  • 减少 CoreData 的调试输出?

    我正在开发一个使用 CoreData 的 iOS macOS 项目 它工作正常 但它会向控制台输出大量调试信息 这使得控制台无法使用 因为我的打印语句隐藏在所有与 CoreData 相关的内容中 我有一个非常简单的 CoreData 设置
  • 哪些 Flutter 插件或功能可以利用外部 iOS/Android 显示器来显示与主显示器不同的内容

    我正在构建一个跨平台应用程序 需要在外部显示器上显示不同的视图 通常通过连接到 LCD 投影仪的 HDMI 适配器电缆连接 Flutter 是否能够在内置的外部显示器上显示不同的屏幕 在现有的 Flutter 插件中还是使用现有的 Flut
  • 水平 UICollectionView 单行布局

    我正在尝试使用以下命令设置简单的水平布局UICollectionView 兜圈子却没有达到预期的结果 所以任何指针或例子将不胜感激 我粘贴经常更改的代码但没有成功可能没什么意义 该图像显示两行 第一行是单个项目 尺寸正确并且在中心正确对齐
  • 如何在 Flutter App 中按时间注销?

    如果用户在登录后对应用程序没有反应或不活动超过 5 分钟 我需要从应用程序中注销用户 该应用程序将转到主登录页面 我尝试实施给定的解决方案here https stackoverflow com questions 52602606 how
  • STM32F4 定时器 - 计算周期和预分频,以生成 1 ms 延迟

    我在用STM32F407VGT6 with CubeMX 因此 我从通用定时器开始 但我被预分频值和周期值所困扰 基本上我想每隔一段时间生成一个定时器中断n 其中 n 1 2 3 ms 并执行一些任务 计算周期和预分频值的公式有很多变化 公
  • 什么是 WKWebView 中的 WKErrorDomain 错误 4

    fatal error LPWebView encounters an error Error Domain WKErrorDomain Code 4 A JavaScript exception occurred UserInfo 0x7

随机推荐

  • 为什么 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