ios - Swift - NSTimer 延迟遍历数组

标签 ios arrays animation swift nstimer

我有一个数组,我希望将 UILabel 的文本设置为数组的一个元素,然后在一秒钟后将文本设置为数组的下一个元素。一旦到达数组的末尾,它就需要返回到开头。我已经尝试使用遍历数组的 for 循环来完成此操作,并在 for 循环内使用延迟函数,但这并不会减慢 for 循环本身的运行速度。我也尝试过使用 NSTimer,

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)

func update() {
    var i = Int()

    UIView.animateWithDuration(0.2, delay: 0.3, options: nil, animations: { () -> Void in

        if i == connectionName.count - 1 {
            i = 0
            println(connectionName[i])
        } else {
            println(connectionName[i])
        }

        }, completion:  { (finished: Bool) -> Void in
            i = i+1
    })

}

但我只是得到一个错误

2015-01-08 15:06:10.511 Tinder[585:10642] -[Tinder.TinderViewController update]: unrecognized selector sent to instance 0x7fae99ead3f0
2015-01-08 15:06:10.612 Tinder[585:10642] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Tinder.TinderViewController update]: unrecognized selector sent to instance 0x7fae99ead3f0'

这是因为该函数是在 View 的 did load 方法中定义的吗?

最佳答案

你问

Is this because the function is defined within the view did load method?

确实是这个问题。 NSTimer 使用 Objective-C 消息传递来调用计时器函数,并且 Swift 中的嵌套函数不会作为 Objective-C 方法公开。 您必须将 update() 定义为 View Controller 类中的顶级函数。

不幸的是,编译器无法警告您,因为它“不知道” 选择器中的字符串“update”对应于 update() 函数。 (与 Objective-C @selector() 不同,Swift 使用简单的字符串作为选择器,编译器 无法验证其存在)。

如果您使用 @objc 显式注释嵌套函数,那么您将得到一个 编译器错误。

关于ios - Swift - NSTimer 延迟遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27843250/

相关文章:

css 关键帧每一步都会停止一秒钟

css - 使用 React 映射图像数组时如何创建图像背景渐变

iphone - iOS 无法在设备旋转时自动调整 subview 的大小

iOS swiftUI 应用警告 RSABSSATokenBlinder 在两个位置实现

java - 要执行的最大任务数

java - 将文本文件读入构造函数数组(java)

ios - “stringByAppendingPathComponent”不可用

ios - 在没有苹果开发者程序或越狱的设备上测试 iOS 应用程序

javascript - 如何计算JavaScript中多个数组的交集?什么是 [等于 : function] mean?

ios - tableView delete动画仅在从底部删除时有效