我正在开发一个测验应用程序,一旦您正确回答问题, View Controller 就会转到另一个 View Controller ,通知用户他们答对了问题并单击按钮继续。但是,当我运行模拟器时,一旦它转到下一个 View Controller ,数据就不会被保存。一旦用户正确回答了一个问题,我希望这个问题不再被问到。但是,到目前为止,一旦您正确回答了一个问题并转到要求您继续的 View Controller ,您按下按钮将返回到原始 View Controller ,系统会向用户询问他们已经回答过的问题。我怎样才能让 View Controller 要求用户继续保存来自原始 View Controller 的数据,以确保不会向用户询问他们已经正确回答的问题?
这是我的原始 View Controller 代码:
import UIKit
class ViewController: UIViewController {
var questionList = [String]()
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "wrongViewSegue", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "rightSeg", sender: self)
}
//variables
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
@IBOutlet weak var questionLabel: UILabel!
//Answer Button
@IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox))
{
print ("Correct!")
}
else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
questionList = []
}
randomQuestion()
}
override func viewDidAppear(_ animated: Bool)
{
randomQuestion()
}
//variables
var seconds = 15
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
这是在您正确回答问题后它会转到的 View Controller 的代码:
import UIKit
class CorrectView: UIViewController {
//correct answer label
@IBOutlet weak var correctLbl: UILabel!
//background photo
@IBOutlet weak var backgroundImage: UIImageView!
func backToQuiz() {
performSegue(withIdentifier: "continueSeg", sender: self)
}
@IBAction func `continue`(_ sender: Any) {
backToQuiz()
}
override func viewDidLoad() {
super.viewDidLoad()
}
最佳答案
以下是您可以存储数据并传递给 viewController 的方法。:-
创建自定义委托(delegate)并将数据从一个 View Controller 发送到 其他。但一旦您退出应用程序,它就不会保留数据。
第二个选项是创建单例,但只有当它是
在需要从代码的任何位置访问数据的地方需要。第三个选项是使用 UserDefaults 或核心数据,但只有在您 想坚持
关于ios - 如何在 View Controller 之间保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270458/