将Int值从一个VC传递到另一个VC

时间:2018-04-15 23:53:24

标签: ios swift4

我尝试使用了使用字符串值的guide,但它并没有帮助。我正在开发一个有8个按钮的应用程序,每个按钮都会分配一个数字,表示在CountdownVC中转换为分钟的秒数。我在点击按钮时尝试传递Int值,并在CountdownVC中将值分配给var seconds = 0

按下MainVC中的按钮时:

@IBAction func oneMinuteBtnPressed(_ sender: Any) {

        let vc = CountdownVC()
        vc.seconds = 60
        performSegue(withIdentifier: "toCountdownVC", sender: self)
    }

我想将指定的值传递给CountdownVC,使其成为var seconds = 60

import UIKit

class CountdownVC: UIViewController {

@IBOutlet weak var countdownLbl: UILabel!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var pauseBtn: UIButton!
@IBOutlet weak var resetBtn: UIButton!

// Variables
var seconds = 0 // This variable will hold the starting value of seconds. It could be any amount over 0
var timer = Timer()
var isTimerRunning = false // This will be used to make sure the only one time is created at a time.
var resumeTapped = false

override func viewDidLoad() {
    super.viewDidLoad()
    pauseBtn.isEnabled = false

}
func runTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(CountdownVC.updateTimer)), userInfo: nil, repeats: true)
    isTimerRunning = true
    pauseBtn.isEnabled = true
}
@objc func updateTimer(){
    if seconds < 1 {
        timer.invalidate()
        //TODO: Send alert to indicate "time is up!"
    } else {
        seconds -= 1 //This will decrement(count down) the seconds.
        countdownLbl.text = timeString(time: TimeInterval(seconds)) //This will update the label
    }
}
func timeString(time: TimeInterval) -> String {

    let hours = Int(time) / 3600
    let minutes = Int(time) / 60 % 60
    let seconds = Int(time) % 60
    return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
}

除了segue部分之外,我上面所做的似乎并不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

正如Quoc Nguyen指出的那样,您正在为永远不会使用的控制器分配值。

当您致电performSegue时,这将实例化您创建的vc。

如果您想将某些内容传递给故事板创建的vc,则需要使用以下内容:

@IBAction func oneMinuteBtnPressed(_ sender: Any) {
        performSegue(withIdentifier: "toCountdownVC", sender: self)
}

 // This function is called before the segue
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // get a reference to the your view controller
     if let nextViewController = segue.destination as? CountdownVC {
        nextViewController.seconds = 60
     }
 }