Я новичок в Свифте и новичок в программировании в целом. Я создаю приложение викторины. Я хочу выбрать тему в TopicViewController и перейти к новому Quizviewcontroller, который будет отображать вопросы и варианты ответов. У меня есть несколько банков вопросов, которые я считаю объектами класса Вопрос. Я могу перейти к QuizViewConctroller с помощью segue, но не могу выбрать банк вопросов на основе выбранной кнопки пользовательского интерфейса темы.
Я пытался и провел дни, пытаясь понять это. Я посмотрел на подобные посты в SO. Я уже писал этот вопрос, но не получил ответа. Буду очень признателен, если кто-нибудь сможет помочь. Я не знаю, как еще действовать ...
TopicsViewController:
import UIKit
class TopicsViewController: UIViewController, ReturnToTopicVCDelegate {
func goToTopicVC() {}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goToQuestionsVCWhenPressed(_ sender: UIButton) {
performSegue(withIdentifier: "segueToQuestionVC", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueToQuestionVC" {
let quizVC = segue.destination as! QuizViewController
quizVC.delegate = self
}
}
}
QuizViewController:
import UIKit
import QuartzCore
protocol ReturnToTopicVCDelegate {
func goToTopicVC()
}
class QuizViewController: UIViewController {
var delegate: ReturnToTopicVCDelegate?
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var questionImageView: UIImageView!
@IBOutlet weak var optionAButton: UIButton!
@IBOutlet weak var optionBButton: UIButton!
@IBOutlet weak var optionCButton: UIButton!
@IBOutlet weak var optionDButton: UIButton!
@IBOutlet weak var optionEButton: UIButton!
//outlets for the progress
@IBOutlet weak var questionCounter: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
var allQuestions = QuestionBank()
var selectedAnswer: Int = 0 // answer selected by the subject
var questionNumber: Int = 0
var score: Int = 0
@IBAction func answerPressed(_ sender: UIButton) {
if sender.tag == selectedAnswer {
print("correct answer")
sender.backgroundColor = .green
score += 1
} else {
print("wrong")
sender.backgroundColor = .red
print("\(allQuestions.list[questionNumber].correctAnswer)")
//the following two lines change the right answer button to green using the tag value of the button
let correctAnswerButton = view.viewWithTag(selectedAnswer) as? UIButton
correctAnswerButton?.backgroundColor = UIColor.green
}
}
@IBAction func GoToNextQuestion(_ sender: UIButton) {
questionNumber += 1
nextQuestion()
}
func nextQuestion() {
if questionNumber <= allQuestions.list.count - 1 {
questionLabel.text = allQuestions.list[questionNumber].question
questionImageView.image = UIImage(named: (allQuestions.list[questionNumber].questionImage))
optionAButton.setTitle(allQuestions.list[questionNumber].optionA, for: .normal)
optionBButton.setTitle(allQuestions.list[questionNumber].optionB, for: .normal)
optionCButton.setTitle(allQuestions.list[questionNumber].optionC, for: .normal)
optionDButton.setTitle(allQuestions.list[questionNumber].optionD, for: .normal)
optionEButton.setTitle(allQuestions.list[questionNumber].optionE, for: .normal)
selectedAnswer = allQuestions.list[questionNumber].correctAnswer
updateUI()
} else {
let alert = UIAlertController(title: "Great!", message: "Do you want to start over?", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart", style: .default) { (UIAlertAction) in
self.restartQuiz()
}
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
}
func updateUI() {
scoreLabel.text = "score: \(score)"
questionCounter.text = "\(questionNumber + 1)/\(allQuestions.list.count)"
}
func restartQuiz() {
score = 0
questionNumber = 0
nextQuestion()
}
@IBAction func goBackToTopicsVC(_ sender: Any) {
delegate?.goToTopicVC()
dismiss(animated: true, completion: nil)
}
}
Вопросы в этом формате
import Foundation
class QuestionBank {
var list = [Question]()
init() {
let skyColorQuestion = Question(questionText: “What is the color of sky?", image: "sky", choiceA: "blue", choiceB: "black", choiceC: "yellow", choiceD: "pink", choiceE: "None of the above", answer: 1)
let whatQuestion = Question(questionText: “what…?”, image: "image", choiceA: "x", choiceB: "y", choiceC: "z", choiceD: "m", choiceE: "None of the above", answer: 3)
list.append(skyColorQuestion)
list.append(whatQuestion)
}
}
Панель навигации
Раскадровка