swift - 如何在一系列问题的标签中显示下一个问题

标签 swift loops if-statement int increment

Screenshot of current code in simulator, once the next button is clicked nothing changes and the question presented in the label remains the same

我正在构建一个调查应用程序,并希望通过标签显示问题列表。但是,我当前的代码功能提出了相同的问题,点击按钮后我需要转到下一个问题。一旦点击按钮,标签就会呈现数组中的下一个问题,并将先前提出的问题移动到数组的末尾。这是我当前的 Swift 代码,用于点击按钮时调用的函数,到目前为止,点击按钮时它会提出相同的问题:

         func nextQuestion() {
    var questions = [choice1, choice2, choice3]
    var y = 0

    questionLbl.text = questions[y].question
    questions.remove(at: y)
    y += 1



    var button = UIButton()
    var tags = [0,1,2,3]

    for quest in questions {

    }

    for idx in tags {
        button = choiceButtons[idx]
        if idx < options.count {
            print("True! Index = \(idx) and options count = \(options.count)")
            button.setTitle(options[idx], for: .normal)

        }
        else {
            print("False! Index = \(idx) and options count = \(options.count)")

        }
    }

    print(questions)


}

这是我的对象模型,其中包含用于问题数组的对象:

      import Foundation

   var choice1 = User.Choice(question: "How old are you?", opt1: "12", opt2: "11", opt3: "10", opt4: "23")
   var choice2 = User.Choice(question: "What color are you?", opt1: "Black", opt2: "White", opt3: "Purple", opt4: "Brown")
   var choice3 = User.Choice(question: "What day is it?", opt1: "Monday", opt2: "Tuesday", opt3: "Friday", opt4: "Sunday")



   var users = [User]()

   struct User {
var fields: Field
var choices = [Choice]()

struct Field {
    var firstname: String
    var lastname: String
    var email: String

    init(first: String, last: String, email: String) {
        self.firstname = first
        self.lastname = last
        self.email = email
    }
}

struct Choice {
    var question: String
    var opt1: String
    var opt2: String
    var opt3: String
    var opt4: String

    init(question:String, opt1: String, opt2: String, opt3: String, opt4: String) {
        self.question = question
        self.opt1 = opt1
        self.opt2 = opt2
        self.opt3 = opt3
        self.opt4 = opt4
    }
}

}

最佳答案

您在 nextQuestion 方法中将 y 设置为 0,这每次都会重置计数:

var y = 0

questionLbl.text = questions[y].question
questions.remove(at: y)
y += 1

所以你总是得到问题数组中的第一个问题。另外,我不知道为什么每次都要从 questions 数组中删除第一项,因为每次调用 nextQuestion 时都会重新创建数组。

关于swift - 如何在一系列问题的标签中显示下一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54514346/

相关文章:

objective-c - OSX 应用程序在某些机器上打开,而不是其他机器

ios - 手腕掉落后用户通知未出现在 watch 上

java - 如何使用一组中的键和另一组中的值填充 HashMap

if-statement - 在 Swift 的 if 语句中使用 let

ios - Swift - 如果语句不能正常工作

linux - Swift objc_sync_enter/exit Linux 替代品

ios - 无法选择 SwiftUI TextField

if-statement - 为什么将最可能的条件放在 `if-else` 语句中?

python - Azure OCR API 在 90 个图像后停止。如何修复连接错误?

python - 如何循环 python 读取一组 HTML 文件并转储到 JSON