我在viewDidLoad中有许多初始设置:
countDownLabel.alpha = 1
countDownLabel.text = "01:30"
swipeLeft.alpha = 0
swipeRight.alpha = 0
pressPlayToStartOr.alpha = 0
swipeToChangeTheSeq.alpha = 0
countDownPauseLbl.alpha = 0
我有一个NSTimer(我把定时器的func update()放在viewDidLoad里面,而它是由viewDidLoad外的UIButton触发的)。当我从UI视图控制器中切换时,计时器继续运行。当我回到定时器视图控制器时,我可以听到定时器运行的声音,但定时器视图控制器刷新到它的初始状态,你可以再次运行定时器,使它们重叠。计时器结束后的程序性segue在这种情况下不起作用。我知道我可能使用了错误的方法,但希望它可以修复。无论我在应用程序中的哪个位置,如何更新标签。
答案 0 :(得分:1)
效果:
在SingletonTimer.swift
:
//
// SingletonTimer.swift
// testSwiftUITextField
//
// Created by leo on 2016/12/17.
// Copyright © 2016年 leo. All rights reserved.
//
import UIKit
class SingletonTimer: NSObject {
private static let sharedInstance = SingletonTimer()
class var sharedSingletonTimer:SingletonTimer {
return sharedInstance
}
var timeCount:Int = 100
func countDown() {
timeCount -= 1
timer_closure(timeCount)
}
lazy var timer:Timer = {
var timer:Timer
if #available(iOS 10.0, *) {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
self.countDown()
})
} else {
// Fallback on earlier versions
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
}
return timer
}()
var timer_closure:(Int)->Void = { (count) in
}
}
在ViewController.swift
:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
在ViewController2.swift
:
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var label: UILabel!
var timer:Timer? = nil
override func viewDidLoad() {
super.viewDidLoad()
timer = SingletonTimer.sharedSingletonTimer.timer
SingletonTimer.sharedSingletonTimer.timer_closure = { (timeCount) in
print("\(timeCount)")
self.label.text = "\(timeCount)s !"
}
if timer != nil {
timer?.fire()
}
}
}