我知道如何將數據傳遞給新的ViewController。問題是我似乎無法從計時器內傳遞數據。如何將計時器中的數據傳遞給新的ViewController(Swift 3)
以下代碼適用於一個ViewController。我嘗試了多種方法將代碼拆分爲兩個視圖控制器。我已經嘗試將計時器放在SecondViewController中。我試過只傳遞最初的datePicker。我曾嘗試將函數放入函數中。
目前的問題是我無法傳遞totalSeconds,因爲它是在定時器內定義的。如果我初始化定時器之外的函數,比如說0,它只是返回一個值0.如果我通過datePicker或date組件,當我在SecondViewController中定義時間間隔時遇到類似的問題。例如,updateTimer函數不會識別傳遞給SecondViewController的ViewDidLoad()的值。
任何幫助,非常感謝。我只想將字符串放在SecondViewController中的updateTimer()中。
class ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var Output: UILabel!
@IBOutlet weak var Output4: UILabel!
@IBOutlet weak var Output3: UILabel!
@IBOutlet weak var Output2: UILabel!
@IBOutlet weak var timePicker: UIDatePicker!
@IBOutlet weak var Output5: UILabel!
@IBOutlet weak var Output6: UILabel!
var birthDate = DateComponents()
@IBAction func timePickerChanged(_ sender: Any) {
let tComponents = Calendar.current.dateComponents([.hour, .minute], from: (sender as AnyObject).date)
birthDate.hour = tComponents.hour
birthDate.minute = tComponents.minute
}
@IBAction func datePickerChanged(_ sender: Any) {
let components = Calendar.current.dateComponents([.year, .month, .day], from: (sender as AnyObject).date)
birthDate.year = components.year
birthDate.month = components.month
birthDate.day = components.day
}
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a nib.
}
func updateTimer(){
let now = Date()
let birthDay = userCalendar.date(from: birthDate)!
let totalSeconds = Int(now.timeIntervalSince(birthDay))
let totalMinutes = userCalendar.dateComponents([.minute], from: birthDay, to: now)
let totalHours = userCalendar.dateComponents([.hour], from: birthDay, to: now)
let totalDays = userCalendar.dateComponents([.day], from: birthDay, to: now)
let totalWeeks = userCalendar.dateComponents([.weekOfYear],from: birthDay, to: now)
let totalMonths = userCalendar.dateComponents([.month], from: birthDay, to: now)
Output.text = String(totalSeconds)
if totalMinutes.minute != nil {
Output2.text = String(totalMinutes.minute!)
}
if totalHours.hour != nil {
Output3.text = String(totalHours.hour!)
}
if totalDays.day != nil{
Output4.text = String(totalDays.day!)
}
if totalWeeks.weekOfYear != nil{
Output5.text = String(totalWeeks.weekOfYear!)
}
if totalMonths.month != nil{
Output6.text = String(totalMonths.month!)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
updateTimer()
let secondsController = segue.destination as! SecondViewController
secondsController.finalSeconds = totalSeconds
}
非常感謝。會嘗試。編程和iOS新手,所以我沒有聽說過協議和代表。 – CJW