Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 想了解一段关系吗_Swift - Fatal编程技术网

Swift 想了解一段关系吗

Swift 想了解一段关系吗,swift,Swift,我是一个在Xcode 8中学习Swift 3的初学者,当时我正在开发一个名为“Eggtimer”的基本应用程序。代码写在下面,我不明白timerlabel.text是如何链接到计时器的,即使我没有在它们之间设置任何连接 在星号/*旁边,我们还可以写}或者{timer.invalidate()和标签timer.text很好地停止减少,这是如何发生的?计时器属性中的选择器意味着什么? 对不起我的英语,谢谢你的回答 class ViewController: UIViewController {

我是一个在Xcode 8中学习Swift 3的初学者,当时我正在开发一个名为“Eggtimer”的基本应用程序。代码写在下面,我不明白
timerlabel.text
是如何链接到计时器的,即使我没有在它们之间设置任何连接

在星号
/*
旁边,我们还可以写
}或者{timer.invalidate()
标签timer.text
很好地停止减少,这是如何发生的?计时器
属性中的
选择器
意味着什么? 对不起我的英语,谢谢你的回答

class ViewController: UIViewController {
    var timer = Timer()
    var time = 210

    func decreasetimer() {
        if time > 0 {
            time -= 1
            timerlabel.text = String(time)
        } else { //*
            timerlabel.text = String(time)
        }
    }

    @IBOutlet var timerlabel: UILabel!

    @IBAction func timerstarter(_ sender: AnyObject) {        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processtimer), userInfo: nil, repeats: true)
    }
}     

让我们从底部开始:
选择器
指定应每1秒调用一次的方法(
时间间隔
参数)。在您的情况下,应将其更改为以下内容:

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.decreasetimer), userInfo: nil, repeats: true)
如您所见,
选择器
称为
递减计时器
,这是您在顶部指定的方法

计时器现在在每次更新时都会调用此方法。在此方法中,可以减少
时间
变量并更新
计时器标签的文本

timer.invalidate()
time
达到0时停止
timer


我希望这能澄清您的问题。

在执行代码时,计时器会等待一定的时间间隔,然后触发,向目标对象发送指定的消息。这里,时间间隔为1。目标是ViewController对象。消息将发送到选择器中的函数。我相信您已经知道为了更好地理解它是如何工作的,我建议你看一下关于运行循环的文档。如果你看一下例如
-processtimer(:)
method的body您可能会看到它们之间的一些联系;当前的代码片段根本没有显示该方法,您可能忘记了向我们显示。谢谢您,Hannes。听起来计时器好像在扮演“While…”的角色,但有固定的时间间隔。