[BMI계산기3] Segues & Navigation

Lena·2022년 1월 13일
0

iOS앱개발 입문기

목록 보기
16/17

지난 시간에 ViewController에서 직접 코딩하여 subview를 생성했다면 이번에는 storyboard에서 생성해보자.

Segues

파일 생성하기

  • file - new - cocoa touch class - UIViewController
import UIKit

class _ResultViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
  • 아까는 직접 정의해주었던 부분들이 자동으로 세팅되어있다.

SubView와 ViewController 연결하기

  • 계산 결과값을 IBOutlet 연결 (bmiLabel)
  • 결과값에 따라 출력되는 advice 문구 또한 IBOutlet 연결 (adviceLabel)

Segue (세그웨이) 생성하기

Segue 세그웨이

  • 세그웨이를 통한 화면 전환
    스토리보드를 통해 출발지와 목적지를 직접 지정하는 방식
  • 세그웨이
    두 개의 뷰 컨트롤러 사이에 연결된 화면 전환 객체
  • 객체 생성 방법

    present Modally 선택

  • 위 화면처럼 화살표 안 사각형을 누르면 화면전환 종류 (transition Types) 를 수정할 수 있다.
  • 화살표는 세그웨이의 흐름 방향을 나타낸다.
  • Segue의 Identifier의 이름을 goToResult로 변경한다.

bmi 결과값 subview에 출력하기

  • calculateViewController 클래스에서 bmiValue 초기화
    var bmiValue = "0.0"
  • segue prepare 함수에서 bmiValue의 destination 값 변경해주기
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToResult"{
            let destinationVC = segue.destination as! ResultViewController
            destinationVC.bmiValue = bmiValue
        }
    }
  • resultViewController 클래스에서 viewDidLoad 함수에 bmiValue 값을 bmi label의 text property로 넣어준다.
    override func viewDidLoad() {
        super.viewDidLoad()
        
        bmiLabel.text = bmiValue
    }

recalculate 버튼 실행해서 이전으로 돌아가기

  • resultViewController 에서 다음과 같이 recalculatePressed 함수를 완성한다.
    @IBAction func recalculatePressed(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }

MVC 패턴 적용 및 결과물

Model - CalculatorBrain



import UIKit

struct CalculatorBrain {

    var bmi:BMI?

    func getBMIValue() -> String{
        
        let bmiTo1DecimalPlace = String(format: "%.1f", bmi?.value ?? 0.0)
            return bmiTo1DecimalPlace
        }
    
    
    func getAdvice() -> String {
        return bmi?.advice ?? "No advice"
    }
    
    
    func getColor() -> UIColor {
        return bmi?.color ?? UIColor.white
    }
    
    mutating func calculateBMI(height: Float, weight: Float) {
        let bmiValue = weight / pow(height, 2)
        // bmi = BMI(value: bmiValue, advice: <#T##String#>, color: <#T##UIColor#>)
        

            if bmiValue < 18.5 {
                bmi = BMI(value: bmiValue, advice: "저체중입니다. 더 많은 음식을 섭취해도 되겠어요!", color: UIColor(red: 0.77, green: 0.87, blue: 0.96, alpha: 1.00))
                
            } else if bmiValue < 24.9 {
                bmi = BMI(value: bmiValue, advice: "정상체중입니다.지금처럼 균형을 유지하세요!", color: UIColor(red: 0.76, green: 0.88, blue: 0.77, alpha: 1.00))
                          
            } else {
                bmi = BMI(value: bmiValue, advice: "과체중입니다. 균형잡힌 식사를 하고, 운동량을 늘리세요!", color: UIColor(red: 0.92, green: 0.59, blue: 0.58, alpha: 1.00))
            }
    }
}

Model- BMI

import UIKit

var calculator = CalculatorBrain()


struct BMI {
    let value: Float
    let advice: String
    let color: UIColor
}

Controllers - calculateViewController

import UIKit

class calculateViewController: UIViewController {
    
    // var bmiValue = "0.0"
    var calculatorBrain = CalculatorBrain()
    
    @IBOutlet weak var heightLabel: UILabel!
    @IBOutlet weak var weightLabel: UILabel!
    
    @IBOutlet weak var heightSlider: UISlider!
    @IBOutlet weak var weightSlider: UISlider!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


    @IBAction func heightSliderChanged(_ sender: UISlider) {
        let height = String(format: "%.2f",  sender.value)
        
        heightLabel.text = "\(height)m"
    }
    
 
    @IBAction func weightSliderChanged(_ sender: UISlider) {
        let weight = String(Int(sender.value))
        
        weightLabel.text = "\(weight)kg"
    }
    
    @IBAction func calculatePressed(_ sender: UIButton) {
        
        let height = heightSlider.value
        // heightSlider의 property 중 value 값
        
        let weight = weightSlider.value
        // weightSlider의 property 중 value 값
        
        /*
        let bmi = weight / pow(height, 2)
        // let bmi = weight / (height * height) 와 동일함
        
        bmiValue = String(format:"%.1f", bmi)
         */
        
        // Model 생성하며 추가해주는 코드
        calculatorBrain.calculateBMI(height: height, weight: weight)
        self.performSegue(withIdentifier: "goToResult", sender: self)
        
      
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToResult"{
            let destinationVC = segue.destination as! ResultViewController
            destinationVC.bmiValue = calculatorBrain.getBMIValue()
            destinationVC.advice = calculatorBrain.getAdvice()
            destinationVC.color = calculatorBrain.getColor()
        }
    }
    // as : Downcasting   
}

Controllers - ResultViewController
import UIKit

class ResultViewController: UIViewController {

    var bmiValue: String?
    var advice: String?
    var color: UIColor?
    
    @IBOutlet weak var bmiLabel: UILabel!
    @IBOutlet weak var adviceLabel: UILabel!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        bmiLabel.text = bmiValue
        adviceLabel.text = advice
        view.backgroundColor = color
    }
    
    @IBAction func recalculatePressed(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}

결과물

0개의 댓글