简体   繁体   中英

How to reload view after data changes in Swift

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.

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.

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()
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM