Swift:其视图不在窗口层次结构中

时间:2016-05-27 04:06:08

标签: ios swift

我知道这被问了很多,但我在这里尝试了很多其他的解决方案,我似乎无法做到正确。

所以,我有一个倒计时的课程,在倒计时结束时,新视图开始。

这是倒计时课程:

import Foundation
import UIKit

class CountdownController: UIViewController {

// MARK: Properties
@IBOutlet weak var countDownLabel: UILabel!


var count = 3

override func viewDidLoad() {
    super.viewDidLoad()


}

override func viewDidAppear(animated: Bool) {
            var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}

func update() {
    if(count > 0) {
        countDownLabel.text = String(count--)
    }
    else {
        self.performSegueWithIdentifier("goestoMathTest", sender: self)

    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: Actions

}

并且MathTestController显示后出现的错误是:

2016-05-26 23:43:48.579 TraderMathTestiOS[18654:951105] Warning: Attempt to 
present <TraderMathTestiOS.MathTestController: 0x7fca824be7d0> on 
<TraderMathTestiOS.CountdownController: 0x7fca824b9d70> whose view is not in 
the window hierarchy!

**编辑:所以我尝试了另一个改变一些事情,我想我缩小了这个问题。我将计时器更改为viewDidLoad()并将重复更改为“false”,现在MathTestController在1秒后出现,没有出现警告。这是更改后的代码:

override func viewDidLoad() {
    super.viewDidLoad()
            var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: false)

}


func update() {
    self.performSegueWithIdentifier("goestoMathTest", sender: self)

    if(count > 0) {
        countDownLabel.text = String(count--)
    }
    else {
        self.performSegueWithIdentifier("goestoMathTest", sender: self)

    }
}

我认为错误显示的原因是因为即使在调用MathTestController之后,计时器仍在CountdownController中重复。任何人都知道如何获得我的原始功能(一个计数'3,2,1'的计时器)没有错误?也许我需要以某种方式杀死计时器?

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题。对于任何想知道的人,如果您的计时器重复,您需要在启动新视图时使其无效。这是固定代码:

class CountdownController: UIViewController {

// MARK: Properties
@IBOutlet weak var countDownLabel: UILabel!
var timer = NSTimer()


var count = 3

override func viewDidLoad() {
    super.viewDidLoad()
            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)

}


func update() {

    if(count > 0) {
        countDownLabel.text = String(count--)
    }
    else {
        timer.invalidate()
        self.performSegueWithIdentifier("goestoMathTest", sender: self)

    }
}