2

I have a view that contains labels, and have a button to change the values of the labels. Instead of changing the values one by one in the button, how can I reload the whole view to update the labels.

@IBOutlet weak var one: UILabel!
    @IBOutlet weak var two: UILabel!
    @IBOutlet weak var three: UILabel!
....
    @IBOutlet weak var updateLabels: UIButton!{
        //doing something to change the value of the labels
        //then wanna reload the whole view
        viewDidLoad()
    }

I had called the viewDidLoad() method, but didn't work.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
Difeng Chen
  • 159
  • 3
  • 10

3 Answers3

4

You should never call viewDidLoad yourself. It's a framework function that the OS calls, as an indication that your views are ready to be setup.

It would serve better if you separated your function

func updateLabels() {
        one.text = "one"
        two.text = "two"
        three.text = "three"
}

and now you can call the updateLabels function when you want.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
1

Why dont you put all labels on a method. and fire it when ever you need to reload.

override func viewDidLoad() {
    super.viewDidLoad()

    updateLabels()

}

func updateLabels() {
    one.text = "one"
    two.text = "two"
    three.text = "three"
}


@IBAction func updateLabels(_ sender: Any) {
       updateLabels()
}
Im Batman
  • 1,842
  • 1
  • 31
  • 48
  • @ShauketSheikh what do you mean by bad approach? when you have initial data you update those in viewDidLoad method and when there is new updated values then fire the same method on any action method to update those. – Im Batman Nov 09 '17 at 04:16
-1

Your method of updating your labels is incorrect. What you need to do is as follows:

Declare your labels like you did ensuring they are linked in Interface Builder:

//Declare The Labels
@IBOutlet var one: UILabel!
@IBOutlet var two: UILabel!
@IBOutlet var three: UILabel!

Then create an IBAction function which is triggered by a UIButton:

/// Set The Text Labels Text
@IBAction func updateLabelText(){

    //Set Label Text
    one.text = "one"
    two.text = "two"
    three.text = "three"
}

Of course remembering to link this to the UIButton instance in Interface Builder.

Hope this helps.

BlackMirrorz
  • 7,217
  • 2
  • 20
  • 31
  • 1
    The user did say that they were trying to trigger this change from a UIButton thus implying an IBAction would be a good way (but not the only way) of handling this. – BlackMirrorz Nov 09 '17 at 03:44