ios - NSTimeInterval 作为倒数计时器,将其作为单独的可重用类应用

标签 ios swift

编辑:我是个白痴。我试图将变量放入 NSTimer()而不是 NSTimeInterval出于任何愚蠢的原因。我想我的问题是如何将所有这些都放在一个单独的类中?

理想情况下,我希望所有这些都包含在一个单独的类 ( CountdownTimer ) 中,这样我就可以创建一个新的计时器实例,但仍保留 NSTimer 的所有功能。包括检查能力 timer.isValid .伪代码看起来像:

var timer = CountdownTimer(countDownFrom: 300) 
timer.start()
timer.isValid()

我的 UIViewController类(不在 viewDidLoad 中):

var totalCountDownTimeInterval = NSTimeInterval(480.0)

var startTime = NSDate()

var timer = NSTimer()
var isRunning = false

func updateTime() {
    var elapsedTime : NSTimeInterval  = NSDate().timeIntervalSinceDate(startTime)
    var remainingTime : NSTimeInterval = totalCountDownTimeInterval - elapsedTime

    if remainingTime <= 0.0 {
        timer.invalidate()
    }

    let minutes = UInt8(remainingTime / 60.0)
    remainingTime = remainingTime - (NSTimeInterval(minutes) * 60)

    let seconds = UInt8(remainingTime)
    println("The time is \(minutes) and \(seconds)")

}


@IBOutlet weak var TimerCount: UILabel!


@IBAction func StartButton(sender: AnyObject) {
    if !timer.valid {
        startTime = NSDate()
        let aSelector : Selector = "updateTime"
        timer = NSTimer.scheduledTimerWithTimeInterval(0.10, target: self, selector: aSelector, userInfo: nil, repeats: true)
    }
}


@IBAction func StopButton(sender: AnyObject) {
    timer.invalidate()
}

@IBAction func ResetButton(sender: AnyObject) {
    timer.invalidate()
    TimerCount.text = "00:00"
}

最佳答案

确保您实际上传递的是 double 值。我喜欢在声明变量时明确说明变量的类型;它有助于避免像这样的问题。

您很可能像这样声明 doubleValue:

let doubleValue = 480

而不是像这样:

let doubleValue = 480.0

或者像这样:

let doubleValue: Double = 480

如果您已正确声明您的变量,这应该工作:

let timeInterval = NSTimeInterval(doubleValue)

如果您要让编译器推断变量的类型,只需确保赋值运算符右侧的任何内容的计算结果都是您要查找的类型。 480 计算为 Int(480)480.0 计算为 Double(480)


编辑:这是您第二个问题的答案:我怎样才能将此 [计时器功能] 包装在一个单独的类中?

其实很简单。假设您想要对类(class)做的就是能够启动它并检查它是否仍然有效,下面是我将如何去做:

class CountdownTimer
{
    var time: NSTimeInterval

    private var startTime: NSDate?

    init(countDownFrom timeInSeconds: Int)
    {
        time = NSTimeInterval(timeInSeconds)
    }

    func start()
    {
        startTime = NSDate()
    }

    func isValid() -> Bool
    {
        if (startTime != nil)
        {
            let timePassed: NSTimeInterval = -(startTime!.timeIntervalSinceNow)

            return timePassed < time
        }
        else
        {
            return false
        }
    }
}

请注意,我几乎没有测试过这个。 Playground 没有提示,从外观上看,这应该可行。现在,只需像这样使用类:

var myCountdownTimer = CountdownTimer(countDownFrom: 300)

// and then whenever we want to start the countdown:

myCountdownTimer.start()

// and then whenever we want to check if the clock's still "ticking", so to speak:

myCountdownTimer.isValid()

// and if we want to restart the timer:

myCountdownTimer.time = NSTimeInterval(900) // we can change the time if we want
myCountdownTimer.start()

本质上,一个 CountdownTimer 对象所做的就是将调用 start() 的确切时间保存到一个名为 startTime 的变量中。请注意,NSDate() 默认设置为它创建的时间和日期。然后 isValid() 简单地检查 timePassed 是否小于计时器设置为倒计时的任何 time;如果是,则返回 true

关于ios - NSTimeInterval 作为倒数计时器,将其作为单独的可重用类应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139783/

相关文章:

ios - 如何在 iOS 中使用 NSUserDafaults 保存和检索 NSObject 类

swift - 如何使用 iOS 9 将单元格 append 到表格 View ?

swift - 基于 Enum Swift 自动为对象赋值

swift - CUI目录 : Invalid Request: requesting subtype without specifying idiom (Where is it coming from and how to fix it? )

ios - 如何避免 Firebase fatal error : unexpectedly found nil while unwrapping an Optional value?

ios - 如何使用 Siri 工具包扩展启用钥匙串(keychain)共享?

ios - 为什么在添加 Alamofire 框架时会出现很多错误?

objective-c - Box2D 编译错误

iphone - 我可以更改通知的字幕吗?

arrays - Index Range Swift 中的新数组