ud788 »

Lesson 1 Code Reference Sheet

This outline is intended as a quick way to reference code snippets. It includes any code you were expected to write yourself and lists files available for download. 

Coding Click Counter

    
override func viewDidLoad() {
    super.viewDidLoad()

    // Allocate and initialize label 
    var label = UILabel()

    // Set label’s frame property
    label.frame = CGRectMake(150, 150,  60, 60)

    // Set text
    label.text = "0"

    // Add label as a subview of the existing view 
    self.view.addSubview(label)
}

Creating the Count and Label Properties

class ViewController: UIViewController {

    //Declare the count and label properties
    var count = 0
    var label:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Allocate and initialize label
        var label = UILabel()

        // Set label’s frame property
        label.frame = CGRectMake(150, 150,  60, 60)

        // Set text
        label.text = "0"

        // Add label as a subview of the existing view
        self.view.addSubview(label)

        // Set the label property equal to the local variable, “label”
        self.label = label

        // Allocate and initialize button. Set frame, title, and title color. 
        var button = UIButton()
        button.frame = CGRectMake(150, 250, 60, 60)
        button.setTitle("Click", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState:.Normal)

        // Add button as a subview of the existing view
        self.view.addSubview(button)
    }

    // Set the label’s text based on the count
    func incrementCount() {
        self.count++
        self.label.text = "\(self.count)"
    }
}

Setting the Target/Action

In the viewDidLoad method of the ViewController.swift file:

// Add the target/action to the button
button.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside)

Transitioning to Storyboard, Label

In the ViewController.swift file:

  • Delete the code inside viewDidLoad.
  • Mark the label property as an IBOutlet so that it appears in Storyboard.
@IBOutlet var label:UILabel!

Transitioning to Storyboard, Connecting a Button

In the ViewController.swift file: Add @IBAction to the front of the incrementCount method so that it is visible to Storyboard.

@IBAction func incrementCount() {
    self.count++
    self.label.text = "\(self.count)"
}

Connecting the Color Maker

Download ColorMaker_incomplete

Debugging Color Maker Error 1

Download Color-Error-1

Debugging Color Maker Error 2

Download ColorMaker-Error-2

Debugging Color Maker Error 3

Download ColorMaker-Error-3

Challenge App: Color Maker with Sliders

Tip on Floats

If you have a Float and you need a CGFloat, you can use the CGFloat constructor to convert between them.
let f: Float = 0.5
let cgf: CGFloat = CGFloat(f)

For a solution, download ColorMaker_Sliders