我尝试按照使用字符串值的本指南进行操作,但没有那么有用。我正在开发一个有 8 个按钮的应用程序,每个按钮都分配有一个数字,表示在 CountdownVC 中转换为分钟的秒数。当我点击一个按钮并将值分配给var seconds = 0
CountdownVC时,我试图传递 Int 值。
在 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 部分,我上面的内容似乎不起作用。任何帮助,将不胜感激。
正如 Quoc Nguyen 指出的那样,您正在为一个永远不会使用的控制器分配一个值。
当您调用 时performSegue
,这将实例化一个与您创建的 vc 不同的 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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句