24.01.12 TIL - Random Colors 3 코드

Hay·2024년 1월 12일
0

iOS Dev Launchpad

목록 보기
3/3

스토리보드

코드

ColorsTableVC

import UIKit

class ColorsTableVC: UIViewController {
    // 1. create an array of colors; since a tableView needs an array of data to display
    var colors: [UIColor] = []
    
    // Refactoring 2. Enum
    enum Cells {
        static let colorCell = "colorCell"
    }
    
    enum Segues {
        static let toDetail = "ToColorsDetailVC"
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 4. call the func
        addRandomColors()
    }
    
    // 3. create a function that creates 50 random colors by using a for loop
    // and the function we just created; createRandomColor()
    func addRandomColors() {
        for _ in 0..<50 {
            // since we wanna add a new color to our colors array, we use append
            //colors.append(createRandomColor())
            // Refactoring 1.
            // replace this with the extension in "UIColor+Ext" as a part of refactoring
            colors.append(.random())
        }
    }
    
    /* 
     Refactoring 1. UIColor+Ext.swift + extension
     Refactoring을 하면서 UIColor+Ext로 스위프트 파일을 따로 만들어서 extension으로 만들어줬기 때문에 주석처리
    // 2. create a function that creates a random color
    // when we run it, it's gonna spit out a random color
    func createRandomColor() -> UIColor {
        // initialize UIColor
        // to throw a random colour, we want a random float from 0 to 1.0
        // -> use "CGFloat.random(in: 0...1)"
        // alpha is opacity. if it's 0, it's completely transparent. if it's 1, it's completely opaque.
        let randomColor = UIColor(red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: 1)
        
        return randomColor
    }
     */
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destVC = segue.destination as! ColorsDetailVC
        //casting -> we need to cast this regular UIViewController as a ColorsDetailVC
        // -> by doing this, this's letting destVC know that it's a ColorsDetailVC
        // -> now we can access that color variable
        destVC.color = sender as? UIColor
        
    }
    
}

// code organization
extension ColorsTableVC: UITableViewDelegate, UITableViewDataSource {
    
    // MARK: - Table view data source
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 5. since we have the colors arrays now, we can return the count of the colors array
        // to make it dynamic instead of passing in a hard number like 50
        return colors.count
    }
    
    // MARK: - Table view delegate
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // delegate method
        // every time a cell is displayed on a screen, this method is called -> delegate method fires off automatically
        
        // 6. a tableview needs to know
        // how many rows i need to show and what i need to show in each row
        // in order to tell it what to show, we need to get access to a cell
        guard let cell = tableView.dequeueReusableCell(withIdentifier: Cells.colorCell) else {
            return UITableViewCell()
        }
        
        let color = colors[indexPath.row]
        // to make it dynamic, we use "indexPath.row" instead of a hard number like 0 or 45, etc.
        // -> this is a part of the delegate method.
        // by passing an indexPath.row, we're telling the tableview whatever row we're on, send that number.
        // if we're on row 47, indexPath.row will equal 47.
        cell.backgroundColor = color
        
        // 위의 코드를 아래와 같이 하나의 line으로 줄일 수 있다.
        //cell?.backgroundColor = color[indexPath.row]
         
        return cell
    }
    
    // didSelectRowAt - this is what happens when we tap on a cell
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let color = colors[indexPath.row]
        performSegue(withIdentifier: Segues.toDetail, sender: color)
    }
}

ColorsDetailVC

import UIKit

class ColorsDetailVC: UIViewController {

    var color: UIColor?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // unwrap the color
        view.backgroundColor = color ?? .blue // giving it a default value by using nil colescing
    }
}

UIColor+Ext

refactoring

// Refactoring 1. UIColor+Ext.swift + extension
import UIKit

extension UIColor {
    // by making it "static", every instance of UIColor can use this function
    // unlike before
   static func random() -> UIColor {
        let randomColor = UIColor(red: CGFloat.random(in: 0...1),
                                  green: CGFloat.random(in: 0...1),
                                  blue: CGFloat.random(in: 0...1),
                                  alpha: 1)
        
        return randomColor
    }
}

0개의 댓글