我正在創建一個簡單的測驗應用程序。有四種選擇,隨機生成選擇的位置。四個UILabel被設置爲顯示選擇。簡單測驗使用arc4random_uniform()
我已經寫了下面的代碼,它通常運行良好,但有時會顯示相同的選擇。
前)2017年2015年2015年1700
誤差應在for循環,但我想不通。
let questions = ["What year is now?"]
let answers = [["2017", "2015", "1000", "1700"]]
var rightAnswerPlacement:UInt32 = 0
var currentQuestion = 0
//Function that displays new question
func newQuestion()
{
lbl.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(4)+1
// Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...4
{
//Create a button
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 = 2
}
}
button.setTitle(answers[currentQuestion][3], for: .normal)
currentQuestion += 1
}
'currentQuestion'在哪裏得到一個值?你用它來查找'answers'中的值,但是你永遠不會給它賦值。 –
對不起,我更新了我的問題 – rebecca87
如果我理解正確,你想要隨機放置第一個答案(正確的一個),其他三個按順序放置?通過循環的四次迭代(btw。不要使用4作爲固定數字,但檢查answers-array的大小),您創建4個按鈕,但使用x-index-counting可以跳過其中一個答案。你還有一個額外的按鈕來回答[currentQuestion] [3] – Gerriet