我知道这个问题被问了很多,但我在这里尝试了很多其他解决方案,但我似乎无法得到正确的答案。
所以,我有一个倒计时的类,在倒计时结束时,一个新的 View 开始。
这是倒计时类:
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”的计时器)而不出现错误吗?也许我需要以某种方式终止计时器?
最佳答案
我终于解决了这个问题。对于任何想知道的人,如果您的计时器重复,则在开始新 View 时需要使其无效。这是固定代码:
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)
}
}
关于ios - Swift:其 View 不在窗口层次结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37474681/