我正在开发一个测验应用程序,一旦你正确回答问题,视图控制器就会转到另一个视图控制器,通知用户他们得到了正确的问题,然后单击按钮继续。但是,当我运行模拟器时,一旦它转移到下一个视图控制器,数据就不会被保存。一旦用户回答了问题,我希望不再问这个问题。但是,截至目前,一旦您回答问题并转向视图控制器,询问您继续问题,您按下按钮以切换回原始视图控制器,用户被问及他们已经回答的问题。如何让视图控制器要求用户继续保存原始视图控制器中的数据,以确保用户不会被问及他们已经正确回答的问题?
这是原始视图控制器的代码:
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.
}
这是正确回答问题后视图控制器的代码:
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()
}
答案 0 :(得分:2)
以下是存储数据并传递给viewController的方法。: -
创建自定义委托并从一个视图控制器发送数据 另一个。但是一旦退出应用程序,它就不会保留数据。
第二个选项是创建单例,但仅在它是
时才这样做
需要从代码中的任何位置访问数据的地方。
第三个选项是使用UserDefaults或核心数据,但仅在您这样做时才这样做 想要坚持
答案 1 :(得分:0)
如果您只想为应用的当前实例化保存以前提出的问题,则可以创建一个单例。这涉及使用包含先前提出的问题的字段创建单独的类。
如果您想在应用终止后保存以前提出的问题,请使用核心数据或用户默认值。