Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.
30,773 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.