반응형
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- Swift Concurrency
- 순환참조
- restful api
- SwiftUI
- swfitui
- 스레드 점유권
- 앱실행
- actor
- task 취소
- navigationview
- unowned
- 격리 시스템
- rest api
- 작업 취소
- StateObject
- REDRAW
- environment object
- 동시성 프로그래밍
- git 명령어
- MVVM
- weak
- environment value
- MainActor
- assosiated type
- NavigationLink
- async/await
- ObservedObject
- Access Control
- Git
- Swift
Archives
- Today
- Total
Develup
[MVVM] MVVM 예제2 본문
반응형
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
반응형
'Swift > MVVM' 카테고리의 다른 글
| [MVVM] MVVM 예제1 (0) | 2021.03.04 |
|---|---|
| [MVVM] MVVM패턴이란? (0) | 2021.03.04 |