簡體   English   中英

Swift-NSTimer延遲循環遍歷數組

[英]Swift - NSTimer to loop through array with delay

我有一個數組,我希望將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'

這是因為函數是在視圖中定義的,方法是否加載方法?

您詢問

這是因為函數是在視圖中定義的,方法是否加載方法?

確實是問題所在。 NSTimer使用Objective-C消息傳遞來調用計時器函數,而Swift中的嵌套函數不會作為Objective-C方法公開。 您必須將update()定義為視圖控制器類中的頂級函數。

不幸的是,編譯器無法警告您,因為它不“知道”選擇器中的字符串“ update”對應於update()函數。 (與Objective-C @selector() ,Swift使用簡單的字符串作為選擇器,並且編譯器無法驗證其存在)。

如果使用@objc顯式注釋嵌套函數, @objc出現編譯器錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM