に答えて、正解はボタンの数でその位置をランダム化します。しかし、現在のコードは、第4の答えを複製しているようです。
これはすべての質問とそれぞれの答えのセットでこれを行います。
ボタンタグは簡単に設定され、最初のタグは「1」とタグ付けされ、2番目のボタンは「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回繰り返されます。 –
x = 1は、正しい答えであるため、配列の0にアクセスしたくないためです。一度しかアクセスする必要はありません。私は値を1から始めます。しかし、最後にx = 3をハードコードしてはいけません。ボタンごとにインクリメントするだけで、文字列配列内を前進する必要があります。 –
"私はハードコードされていてはなりませんx = 3_"、まあ、あなた自身の質問にあなたの答えを得ました。 :) –