IOS Swift Study 11 | MVVM, BountyList 2

SoosDev·2020년 12월 25일
0

IOS Swift Study

목록 보기
11/11
post-thumbnail

MVVM?

MVC와 MVVM 패턴


ViewModel : BountyInfo

BountyViewController.swift

struct BountyInfo

  1. Struct BountyInfo 를 추가합니다.

bountyInfoList

  1. nameList, bountyList를 bountyInfoList로 재구성해줍니다.

prepare for segue

  1. DetailViewController에 값을 전달하는 부분에서는 BountyInfo를 추가함으로 수정합니다.
    (그 전에 DetailViewController 상단에서 var bountyInfo: BountyInfo? 를 추가하고 기존의 var name, bounty를 삭제합니다.)

tableView & count

  1. Cell의 개수는 bountyInfoList의 카운트 되는 만큼의 수만큼

tavleView & cell

  1. 각각의 Cell에 사진과 이름, 가격이 bountyInfo를 통해 불러오도록 수정합니다.
  2. 빌드하여 확인합니다.

DetailViewController.swift

var bountyInfo: BountyInfo?

  1. var bountyInfo: BountyInfo? 를 추가하고 기존의 var name, bounty를 삭제합니다.

updateUI()

  1. updateUI에서 받아온 bountyInfo의 값을 통해 이미지, 이름, 가격 값을 가지기 위해 코드를 수정합니다.

ViewModel : BountyViewModel

BountyViewController.swift

  1. class BountyViewModel을 추가하고 앞서 만들었던 bountyInfoList를 가져와 추가합니다.
  2. 기존 bountyInfoList는 삭제, viewModel을 만들어줍니다.
    ( let viewModel = BountyViewModel )
  3. BountyViewModel 에 리스트의 카운트를 추가해줍니다.
  4. tableView 의 개수를 viewModel에서 가져와줍니다.
  5. BountyViewModel에 List의 index를 return 해주는 func을 추가합니다.
  6. Cell의 위치와 DetailViewController로 보낼 값을 viewModel에서 가져오기 위해 수정합니다.

ViewModel : DetailViewModel

DetailViewController.swift

  1. DetailViewModel을 통해 처리하기 때문에 BountyViewController에서 값을 받아오는 코드도 수정합니다. DetailViewModel에 update func을 추가
  2. BountyViewController의 prepare func에서 update를 통해 전달하도록 수정합니다.
  3. 빌드하여 확인합니다.

View

BountyViewController.swift

ListCell 수정

  1. ListCell 코드 수정
  2. 원래 각 Cell에 이미지, 이름, 가격을 주던 코드를 func update를 추가함으로
    cell.update(info: bountyInfo) 로 대체

BountyViewController.swift

//
//  BountyViewController.swift
//  BountyList
//
//  
//

import UIKit

class BountyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let viewModel = BountyViewModel()
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "showDetail" {
            let vc = segue.destination  as? DetailViewController
            
            if let index = sender as? Int{
                let bountyInfo = viewModel.bountyInfo(at: index)
                vc?.viewModel.update(model: bountyInfo)
     
            }
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return viewModel.numOfBountyInfoList
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ListCell else {
            return UITableViewCell()
        }

        let bountyInfo = viewModel.bountyInfo(at: indexPath.row)

        cell.update(info: bountyInfo)
        return cell
        
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("\(indexPath.row)번 클릭") // 확인
        
        performSegue(withIdentifier: "showDetail", sender: indexPath.row)

    }
}

class ListCell: UITableViewCell {
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var bountyLabel: UILabel!
    
    func update(info: BountyInfo) {
        imgView.image = info.image
        nameLabel.text = info.name
        bountyLabel.text = "\(info.bounty)"
    }
}


struct BountyInfo {
    let name: String
    let bounty: Int
    
    var image: UIImage? {
        return UIImage(named: "\(name).jpg")
    }
    
    init(name: String, bounty: Int) {
        self.name = name
        self.bounty = bounty
    }
}

class BountyViewModel {
    let bountyInfoList: [BountyInfo] = [
        
        BountyInfo(name: "브룩", bounty: 83000000),
        BountyInfo(name: "쵸파", bounty: 100),
        BountyInfo(name: "프랑키", bounty: 94000000),
        BountyInfo(name: "루피", bounty: 1500000000),
        BountyInfo(name: "나미", bounty: 66000000),
        BountyInfo(name: "로빈", bounty: 130000000),
        BountyInfo(name: "상디", bounty: 330000000),
        BountyInfo(name: "조로", bounty: 320000000),
        
    ]
    
    var numOfBountyInfoList: Int {
        return bountyInfoList.count
    }
    
    func bountyInfo(at index: Int) -> BountyInfo{
        return bountyInfoList[index]
    }
}

DetailViewController.swift

//
//  DetailViewController.swift
//  BountyList
//
//  
//

import UIKit

class DetailViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var bountyLabel: UILabel!

    
    let viewModel = DetailViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        updateUI()
    }
    
    func updateUI() {

        if let bountyInfo = viewModel.bountyInfo {
            imgView.image = bountyInfo.image
            nameLabel.text = bountyInfo.name
            bountyLabel.text = "\(bountyInfo.bounty)"
        }

    }
    
    @IBAction func closs(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}


class DetailViewModel {
    var bountyInfo: BountyInfo?
    
    func update(model: BountyInfo?){
        bountyInfo = model
    }
    
}

201224 추가

BountyInfo.swift

새로 Swift 파일을 만들어 BountyViewController에서 struct BountyInfo 부분을 가져와 좀 더 깔끔하게 코드를 볼 수 있게끔 하였습니다.
( 같이 있어도 무방 )


201225 추가

bounty 순서대로 나열 (랭킹?)

BountyViewController - BountyViewModel 에
var sortedList, return sortedList[index] 를 추가하였습니다.

빌드하여 확인하면 전과는 다르게 현상금 금액이 큰 순서대로 나열됩니다.

profile
IOS 개발 공부를 하면서 기록하는 중입니다.

0개의 댓글