使用NSTimer Swift解决未解析的标识符问题

时间:2015-05-26 23:38:06

标签: swift nstimer

我有下面的代码,我发现了一条错误消息。请注意,有问题的代码不在Swift的viewcontroller类中。用于移动的图像代码位于viewdidappear函数中。

var timer = NSTimer(timeInterval:3, target: self, selector:Selector("randomnumbers:"), userInfo: nil, repeats: true)

func randomnumbers(timer:NSTimer) {
    var rockNamesArray:[String] = ["bird", "rock2", "rock3"]    
    var rockpos = Int(arc4random_uniform(UInt32(3)))
}

编辑:

if rockNamesArray[rockpos] == "rock2"  {
        UIView.animateWithDuration(3.0, animations: {
            self.mrock.frame = CGRect(origin: CGPoint(x: 167, y: 600), size: self.mrock.frame.size)
            },
            completion: { _ in
                self.mrock.frame = moriginalFrame
        })

    }

1 个答案:

答案 0 :(得分:0)

首先,您必须在视图控制器类中声明您的计时器:

var timer = NSTimer()
var rockNamesArray:[String] = []
var rockpos = 0

然后在viewDidLoad中安排计时器:

override func viewDidLoad() {
    super.viewDidLoad()
    timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "randomnumbers", userInfo: nil, repeats: true)
}

//

func randomnumbers() {
   rockNamesArray = ["bird", "rock2", "rock3"]    
   rockpos = Int(arc4random_uniform(UInt32(rockNamesArray.count)))
}