본문 바로가기

Mobile/IOS

MVC 패턴

공부하는 것을 정리하는 목적으로 사용하고 있습니다. 건전한 비판은 언제나 환영합니다 ~~

이러한 코드를 만들기 위해서는 main에서 storyboard를 이용해 UI 배치후에

ViewController에다가 코드를 치시면 됩니다.

//
//  ViewController.swift
//  Quizzler-iOS13
//
//  Created by Angela Yu on 12/07/2019.
//  Copyright © 2019 The App Brewery. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var questionLabel: UILabel!
    
    @IBOutlet weak var trueBtn: UIButton!
    
    @IBOutlet weak var falseBtn: UIButton!
    
    @IBOutlet weak var progressBar: UIProgressView!
    
    var questionNumber:Int = 0
    
    let questionList = [Model(question: "A slug's blood is green.", answer: "True"),
    Model(question: "Approximately one quarter of human bones are in the feet.", answer: "True"),
    Model(question: "The total surface area of two human lungs is approximately 70 square metres.", answer: "True"),
    Model(question: "In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.", answer: "False")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        updateUI()
        print("viewDidLoad")
    }

    @IBAction func selectedBtn(_ sender: UIButton) {
        
        let select = sender.currentTitle
        let btn = questionList[questionNumber].answer
        
        if select == btn{
//            print("true")
            trueBtn.backgroundColor = UIColor.green
        }else{
//            print("false")
            falseBtn.backgroundColor = UIColor.red
        }
        
        questionNumber += 1
        questionNumber = questionNumber % questionList.count
//        updateUI()
//        print("selecteBtn")
        Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector( updateUI), userInfo: nil, repeats: false)
    }
    
    @objc func updateUI(){
        questionLabel.text = questionList[questionNumber].question
        trueBtn.backgroundColor = UIColor.clear
        falseBtn.backgroundColor = UIColor.clear
        progressBar.progress = Float(questionNumber)/Float(questionList.count)
    }
    
}

 

- MVC 패턴이란

Model : data 또는 로직을 담당한다.

View : 사용자가 보이는 화면을 View라고 한다.

Controller : View와 Model의 중간사이에서 가교 역할을 한다.

 

 

- 먼저 Model을 분리하겠습니다

//
//  Model.swift
//  Quizzler-iOS13
//
//  Created by Mac on 2022/02/16.
//  Copyright © 2022 The App Brewery. All rights reserved.
//

import Foundation


struct Model{
    
    var question:String
    var answer:String
    
    init(question:String, answer:String){
        self.question = question
        self.answer = answer
    }
    
    
}

위와 같이 모든 문제의 틀을 구하는 방식으로 Model을 만들었습니다.

또 다른 모델은 문제를 보여주기 위한 방식으로 만들었습니다.

//
//  ModelQuiz.swift
//  Quizzler-iOS13
//
//  Created by Mac on 2022/02/16.
//  Copyright © 2022 The App Brewery. All rights reserved.
//

import Foundation


struct ModelQuiz{
    
    var questionNumber:Int = 0
    var quizCount:Int = 0
    
    let questionList = [Model(question: "A slug's blood is green.", answer: "True"),
    Model(question: "Approximately one quarter of human bones are in the feet.", answer: "True"),
    Model(question: "The total surface area of two human lungs is approximately 70 square metres.", answer: "True"),
    Model(question: "In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.", answer: "False")]
    
    
    func quizAnswer(_ str : String) -> Bool{
        
        if str == questionList[questionNumber].answer{
            return true
        }else{
            return false
        }
    }
    
    func quizList()->String{
        return questionList[questionNumber].question
    }
    
    func progressGet() -> Float{
        return Float(questionNumber)/Float(questionList.count)
    }
    
    mutating func numberCount(){
        questionNumber += 1
        questionNumber = questionNumber%questionList.count
    }
    
    func quizNumber() -> Int{
        return quizCount
    }
    
}

데이터와 관련된 로직을 model에다가 다 넣어놨습니다.

 

그리고 이전 ViewController와 Model을 만들고 난 후의 ViewController를 비교하며 설명하겠습니다.

//
//  ViewController.swift
//  Quizzler-iOS13
//
//  Created by Angela Yu on 12/07/2019.
//  Copyright © 2019 The App Brewery. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var questionLabel: UILabel!
    
    @IBOutlet weak var trueBtn: UIButton!
    
    @IBOutlet weak var falseBtn: UIButton!
    
    @IBOutlet weak var progressBar: UIProgressView!
    
    var quiz = ModelQuiz()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        updateUI()
        print("viewDidLoad")
    }

    @IBAction func selectedBtn(_ sender: UIButton) {
        
        let select = sender.currentTitle!
        let btn = quiz.quizAnswer(select)//Model에 있는 글자와 비교하여 True, False 리턴하게 만들었습니다
        
        if btn{// true
            trueBtn.backgroundColor = UIColor.green
        }else{// false
            falseBtn.backgroundColor = UIColor.red
        }
        

        quiz.numberCount()// MOdel안에 있는 number를 증가합니다.
        Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector( updateUI), userInfo: nil, repeats: false)
    }
    
    @objc func updateUI(){
        questionLabel.text = quiz.quizList()//Model안에 있는 문제를 제공합니다
        trueBtn.backgroundColor = UIColor.clear
        falseBtn.backgroundColor = UIColor.clear
        progressBar.progress = quiz.progressGet()//Model 안에서 프로그래스바의 진행사항을 확인합니다.
    }
    
}

이렇게 ViewController에서 간소하게 끝낼 수 있습니다.

'Mobile > IOS' 카테고리의 다른 글

UserDefaults 및 싱글톤  (0) 2022.03.04
다크모드와 벡터 작업  (0) 2022.02.22
ViewController 특징 및 생명주기  (0) 2022.02.08
[IOS] 앱의 생명주기(LifeCycle)  (0) 2022.02.07
class 'ViewController.swift' has no initializers  (0) 2022.02.07