loading...

Navigation Controller Practice

casualty profile image Thomas Dye ・1 min read

Rainbow

This project was intended to help better understand the navigation controller

Feel free to clone and check it out for yourself. This is a good building ground for learning how to make an app with multiple pages.




This is where we will create our array of colors using [MyColor] as the type to return numberOfRowsInSection as colors.count (this .count is referring to each color we will store in the var colors)

import UIKit

class ColorsTableViewController: UITableViewController {

    var colors: [MyColor] = [MyColor(name: "Red", color: .red),
                             MyColor(name: "Orange", color: .orange),
                             MyColor(name: "Yellow", color: .yellow),
                             MyColor(name: "Green", color: .green),
                             MyColor(name: "Blue", color: .blue),
                             MyColor(name: "Cyan", color: .cyan),
                             MyColor(name: "Purple", color: .purple)]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return colors.count
    }

Under cellForRowAt, we want to replace "ReuseIdentifier" with something unique that relates to our project. For this instance, we'll use "ColorCell", but that leaves us with one problem. We need to set our new identifier to the same value of ColorCell. This is found by selecting the prototype cell on your Main.storyboard file, selecting the 'attributes inspector' and setting the identifier to ColorCell.

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell", for: indexPath)

        let color = colors[indexPath.row]

        cell.textLabel?.text = color.name

        return cell
    }

    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "ShowColorSegue" {

            guard let indexPath = tableView.indexPathForSelectedRow,
                let colorDetailVC = segue.destination as? ColorDetailViewController else { return }

            let cellColor = colors[indexPath.row]

            colorDetailVC.cellColor = cellColor

        }
    }
}

Posted on by:

Discussion

pic
Editor guide