Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

swift - make a button display an element each time its pressed

I am new to Swift, and I am trying to make a basic question answer app. I want to set up the question button so that whenever I press it, it displays one question, and if I press it again, it shows another question. I have a separate button that will show the answer but I need to connect to which ever question is being asked. How do I do this?

Here is what I have so far, it just asks the question at random, but I want to be able to ask all the questions, not just whatever it picks, I am not sure how to do that though.

    @IBAction func question(_ sender: Any) {
        let questions = ["What is your name?", "What is your favourite colour?",
            "What is your favourite movie?", "What is your major?"]
        let randomQuestion = questions.randomElement()
        qLabel.text = randomQuestion
    }
question from:https://stackoverflow.com/questions/65878265/make-a-button-display-an-element-each-time-its-pressed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try

var index = 0 // add a current index of the shown question
let questions = ["What is your name?", "What is your favourite colour?",
        "What is your favourite movie?", "What is your major?"]
@IBAction func question(_ sender: Any) {  
    if index < questions.count {  
      qLabel.text = questions[index] 
      index += 1
    }
    else { 
      // end of questions 
   }
   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...