Details for a topic

ViewControllers, UIButton, UILabel

Learn basic functions for UIKit development.

All cards

Dismiss a ViewController

self.dismiss(animated: true, completion: nil)

Declare an IBOutlet for a UIButton

@IBOutlet var myButton: UIButton!

Since we unwrapped it, the IBOutlet has to be connected to an object in Interface Builder, otherwise it creates an Error at runtime.

An optional UIButton? can also be used


Add a subview to a view

myView.addSubview(mySubView)

How to intercept the transition from a ViewController to another one, when using a Storyboard ?

Define an identifier to the Storyboard Segue in Interface Builder

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueName" {
// do something
     }
  }

The view LifeCycle


Change the color of the background of the view to the color blue.

self.view.backgroundColor = UIColor.blue
// or
self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 1, alpha: 1)

Change the text of a UIButton for the normal state

myButton.setTitle("Hello", for: .normal)
// and not myButton.text = ...

Change the background image for a UIButton

let myImage = UIImage(named: "myimage.png")
myButton.setBackgroundImage(myImage, for: .normal)

Set the text for a UILabel

myLabel.text = "Hello"

Automatically adjust the font size of a label to fit content

myLabel.adjustsFontSizeToFitWidth = true

Change the color of a UILabel

myLabel.textColor = UIColor.red

Where should should you place init actions that need to be performed only once for a ViewController?

in viewDidLoad


Where should you place actions that need to be performed every time a ViewController appears?

in viewWillAppear or viewDidAppear


Create a function that will be callable from an object in Interface Builder

@IBAction func myAction () {
}