Swift/MVVM

[MVVM] MVVM 예제2

앱붕이 2021. 3. 8. 04:12

Model

import Foundation

class Person : NSObject{
    var name : String = ""
    var age : Int = 0
    var weight : Double = 0
    var height : Double = 0
    init(name : String, age : Int, weight : Double, height : Double) {
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height
    }
}
class Model : NSObject{
    func getPeopleData() -> NSDictionary {
        return  [
            "People" : [
                ["name" : "James", "age" : 28 , "weight" : 80, "height" : 167.5],
                ["name" : "Lily", "age" : 32 , "weight" : 60, "height" : 180.2],
                ["name" : "Peter", "age" : 24 , "weight" : 70, "height" : 175.4],
                ["name" : "John", "age" : 43 , "weight" : 50, "height" : 156.9],
            ],
        ]
    }
}

View

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var infoTableView: UITableView!

    let viewModel = MVVMViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        infoTableView.delegate = self
        infoTableView.dataSource = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.peopleData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = viewModel.peopleData[indexPath.row] as! Person
        let cell = tableView.dequeueReusableCell(withIdentifier: "InfoTableViewCell") as! InfoTableViewCell
        cell.nameLabel.text = person.name
        cell.ageLabel.text = "\(person.age)"
        cell.etcLabel.text = "\(person.height) / \(person.weight)"
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
}

ViewModel

class MVVMViewModel : NSObject {
    let model : Model = Model()
    var peopleData : NSArray!

    override init() {
        let data1 = model.getPeopleData()["People"] as! NSArray
        let data2 = NSMutableArray()
        for i in 0..<data1.count {
            let tmpData = data1[i] as! NSDictionary
            let name = tmpData["name"] as! String
            let age = tmpData["age"] as! Int
            let weight = tmpData["weight"] as! Double
            let height = tmpData["height"] as! Double
            data2.add(Person(name: name, age: age, weight: weight, height: height))
        }
        peopleData = NSArray(array: data2)
    }
}

완성 화면

reference

HOB

'Swift > MVVM' 카테고리의 다른 글

[MVVM] MVVM 예제1  (0) 2021.03.04
[MVVM] MVVM패턴이란?  (0) 2021.03.04