iosswiftxcodeviewdidload

Place references to IBOutlet and IBAction inside viewDidLoad or just before?


I understand that viewDidLoad is where you are supposed to put any set up code in relation to buttons, color, and other view related code. However, in a code sample I have just seen, a reference to IBOutlet and to IBAction are not written inside of viewDidLoad but rather, just before this method, as below. Are these not set up related code, as in creating a label and a method to manipulate it?

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var nameLabel: UILabel!
@IBAction func showName(sender: AnyObject) {
    nameLabel.text = "my name is Cyril"
}


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

Solution

  • ViewDidLoad is only one method of setup. You can put some code here, local variables, ets. @IBOutlet and @IBAction are links of Interface Builder and nameLabel. And this outlet and action suppose to be global, so you could use them in other functions, not only in viewDidLoad.

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var nameLabel: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            nameLabel.text = "my name is Cyril"
        }
    
    }