我是一个编程新手& 有困难移动到下一个问题答案在我的测验数组使用一个表视图与自定义单元格& 一个下一个按钮。
我的设置。
采取的步骤。
我怎么做。
阵列
struct DataBrain {
var questionNumber: Int? = 0
var dataArray: [MultipleChoice] = [MultipleChoice(question: "What force is opposite to gravity?", options: ["Lift", "Thrust", "Drag", "Gravity"], rightAnswer: "Lift"), MultipleChoice(question: "What is 1 x 3", options: ["1", "2", "3", "4"], rightAnswer: "3"), MultipleChoice(question: "What does MEA stand for?", options: ["My Eating Area", "My Entering Area", "Minimum Entering Area", "None of the above"], rightAnswer: "None of the above")
带有表格视图、自定义单元格和下一步按钮的视图控制器。
class MultipuleChoiceViewController: UIViewController {
@IBOutlet weak var nextButton: LongButtons!
@IBOutlet weak var table: UITableView!
var dataBrain = DataBrain()
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
table.delegate = self
table.register(QuestionTableViewCell.nib(), forCellReuseIdentifier: QuestionTableViewCell.identifier)
table.register(AnswerTableViewCell.nib(), forCellReuseIdentifier: AnswerTableViewCell.identifier)
}
@IBAction func nextButtonPressed(_ sender: Any) {
if var index = dataBrain.questionNumber {
if index + 1 < dataBrain.dataArray.count {
index += 1
} else {
performSegue(withIdentifier: "MultipleChoiceToResults", sender: self)
}
}
}
}
// MARK: - TableView DataSource:
extension MultipuleChoiceViewController: UITableViewDataSource {
//Number of Rows:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let index = dataBrain.questionNumber {
let data = dataBrain.dataArray[index]
if let count = data.options?.count {
return count + 1
}
}
return 0
}
//Return a Cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: QuestionTableViewCell.identifier) as! QuestionTableViewCell
if let index = dataBrain.questionNumber {
let data = dataBrain.dataArray[index]
cell.questionLabel.text = data.question
print (dataBrain.dataArray[index])
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: AnswerTableViewCell.identifier) as! AnswerTableViewCell
if let index = dataBrain.questionNumber {
let data = dataBrain.dataArray[index]
cell.answerLabel.text = data.options![indexPath.row - 1]
}
return cell
}
}
}
// MARK: - TableView Delegate
extension MultipuleChoiceViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
更新你的下一个按钮选择器
@IBAction func nextButtonPressed(_ sender: Any) {
if var index = dataBrain.questionNumber {
if index + 1 < dataBrain.dataArray.count {
index += 1
dataBrain.questionNumber = index
table.reloadData()
} else {
performSegue(withIdentifier: "MultipleChoiceToResults", sender: self)
}
}