0

I am very new to programming in XCode and have been creating small little apps that allow me to understand XCode & Swift in general. Currently I am making a question app that allows the user to press a button, checks if the answer is correct and depending on whether it is or not it will change the view to one of two, the correct or incorrect view.

Here is the storyboard: Storyboard Layout

Now, transition between the different views is fine, however when I go back to the main view from either the incorrect or correct view the label is reset back to the original label shown in the storyboard.

How can I make it so that when I change back to the main view from either the correct or incorrect views, the label stays on the same question shown before moving views.

Here is my Code: https://codedump.io/share/1EgsRsJOUUbY/1/first-app

Any help would be great!

~ Alex

Alex Marchant
  • 570
  • 6
  • 21

1 Answers1

0

Solution

A simple solution would be to override a method named viewDidLoad in your code and set the text of your questionLabel there.

override func viewDidLoad() {
    super.viewDidLoad()

    // You can use any index here. With little effort you can even randomize this.
    let exampleIndex = 0

    questionLabel.text = questions[exampleIndex]
}

Explanation

The problem with your original code is that you haven't set the text of the questionLabel programmatically when the main view appears. By only setting the text in the nextQuestionButton IBaction, your text label will change only if the action is called (which is triggered by pressing the next button I assume). Thus, the text you set from the storyboard was shown.

For a quick review of app view life cycle you can refer to this link.

Community
  • 1
  • 1
saugat gautam
  • 324
  • 2
  • 8
  • How and where do I call this function? – Alex Marchant Apr 03 '17 at 16:38
  • This method gets called automatically. I strongly suggest you to research some more on ViewController lifecycle. Checkout this link for starters http://roadfiresoftware.com/2015/01/ios-essentials-the-uiviewcontroller-lifecycle/ – saugat gautam Apr 04 '17 at 04:32