iOS Build a Simple iPhone App with Swift View Controllers and Views Using IBAction to Execute Methods

dakota ferrell
dakota ferrell
2,336 Points

where to put IBActions?

in the video our ViewController.swift is written like this. The outlet for the label we were shown to put at the top under the class but the video also shows that the IBAction for our button is written under the viewDidLoad() and the didReciveMemoeryWarning. Is there any reason why this is done or could i just as easily put it the buttons IBAction beside the IBOutlet for the label?

import UIKit

class ViewController: UIViewController { @IBOutlet weak var funFactLable: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    funFactLable.text = "An Interesting Fact!"

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func ShowFact() {
}

}

1 Answer

Nathan F.
Nathan F.
iOS Development with Swift Techdegree Student 28,947 Points

You could absolutely put IBOutlets and IBActions next to each other, but the reason we place these things in this order is for readability and convention. Let's ignore UIKit for a moment and look at a simple struct:

struct Car {
  let make: String
  let model: String
  let year: Int
  let numberOfDoors: Int

  func drive() {
     // something to make it drive.
  }

  func beepHorn() {
    print("HONK!")
  }
}

Our variables at the top are properties. At the bottom, we have two functions or methods -- drive and beepHorn. As developers, we group things in this way so we can quickly see all the properties and methods of our types without being confused.

IBOutlets are a property of your class. IBActions are functions / methods that are triggered by interacting with your UI, like tapping a button. So we typically group them in the same way.