这是我的代码,正确答案应该在按钮数量中随机分布,但是当前代码似乎会复制第四个答案。
每个问题及其相应的答案都会出现此问题。
按钮标签设置很简单,第一个按钮标记为“1”,第二个按钮标记为“2”,以此类推。
如果需要更多信息,请随时提问。
我已经留下了有问题的代码,这样其他遇到类似问题的人就可以看到我哪里做错了。
问题代码:
//
// AnimalViewController.swift
// It's Trival
//
// Created by Chris Levely on 12/18/16.
// Copyright © 2016 ZenithNomad. All rights reserved.
//
import UIKit
class AnimalViewController: UIViewController {
let questions = ["What is the fastest fish in the sea?", "Which animal has the most legs?"]
let answers = [["Sailfish", "Tuna", "Swordfish", "Marlin"], ["Millipede", "Spider", "Ant", "Octopus"]]
var currentQuestion = 0
var rightAnswerPlacement : UInt32 = 0
@IBOutlet weak var Question: UILabel!
@IBAction func AnswerQuestion(_ sender: AnyObject)
{
if (sender.tag == Int(rightAnswerPlacement))
{
print("Right")
}
else
{
print("Wrong")
}
if (currentQuestion != questions.count)
{
newQuestion()
}
}
func newQuestion()
{
Question.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(4)+1
var button : UIButton = UIButton()
var x = 1
for i in 1...4
{
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement))
{
button.setTitle(answers[currentQuestion][0], for: .normal)
}
else
{
button.setTitle(answers[currentQuestion][x], for: .normal)
x = 3
}
}
currentQuestion += 1
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
}
新的固定代码:
//
// AnimalViewController.swift
// It's Trival
//
// Created by Chris Levely on 12/18/16.
// Copyright © 2016 ZenithNomad. All rights reserved.
//
import UIKit
class AnimalViewController: UIViewController {
let questions = ["What is the fastest fish in the sea?", "Which animal has the most legs?"]
let answers = [["Sailfish", "Tuna", "Swordfish", "Marlin"], ["Millipede", "Spider", "Ant", "Octopus"]]
var currentQuestion = 0
var rightAnswerPlacement : UInt32 = 0
@IBOutlet weak var Question: UILabel!
@IBAction func AnswerQuestion(_ sender: AnyObject)
{
if (sender.tag == Int(rightAnswerPlacement))
{
print("Right")
}
else
{
print("Wrong")
}
if (currentQuestion != questions.count)
{
newQuestion()
}
}
func newQuestion()
{
Question.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(4)+1
var button : UIButton = UIButton()
var x = 1
for i in 1...4
{
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement))
{
button.setTitle(answers[currentQuestion][0], for: .normal)
}
else
{
button.setTitle(answers[currentQuestion][x], for: .normal)
x += 1
}
}
currentQuestion += 1
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
}
answers[currentQuestion][x]
?第一次硬编码的x
为1,之后每次都是3? - Cœur