[3주차] Life Cycle

Seoyoung Lee·2023년 1월 13일
0

UMC

목록 보기
3/8
post-thumbnail

Standard Mission
TextField로 데이터 입력받아 Life Cycle 활용해 다른 View에 데이터 전달해보기
(실습 내용에 이어서 사칙연산 등 다양한 계산 활용해보기)
✅ 화면 전환 구현
✅ Life Cycle 활용해 다른 View에 데이터 전달

결과 화면

사용한 컴포넌트

  • UILabel : 타이틀 부분, 계산 결과 부분
    • 폰트 사이즈, 스타일(Bold) 속성 변경
  • UIImageView : 곰인형 이미지
  • UITextField : 숫자 입력 부분
    • placeholder 설정
  • UIButton : 사칙연산 버튼, 다시 할래요 버튼
    • background color, tint color 설정

첫 번째 View Controller (ViewController.swift)

@IBOutlet var firstTextField: UITextField!
@IBOutlet var secondTextField: UITextField!

@IBAction func addButtonTapped(_ sender: Any) {
	presentSecondViewController(type: .add)
}
    
@IBAction func subButtonTapped(_ sender: Any) {
	presentSecondViewController(type: .sub)
}
    
@IBAction func mulButtonTapped(_ sender: Any) {
	presentSecondViewController(type: .mul)
}
    
@IBAction func divButtonTapped(_ sender: Any) {
	presentSecondViewController(type: .div)
}

text field는 @IBOutlet, button은 @IBAction 사용

func presentSecondViewController(type: Calculation) {
	guard let secondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else {
		return
	}
	secondViewController.result = calculate(type: type)
	secondViewController.modalPresentationStyle = .fullScreen
	self.present(secondViewController, animated: true, completion: nil)
}

사칙연산 결과를 계산하는 부분과 화면 전환하는 부분이 중복되는 것 같아서 각각 calculatepresentSecondViewController 라는 메소드를 만들어서 분리했다.

계산 결과 문장(0 + 0 = 0 입니다) 전체를 SecondViewController의 result 프로퍼티에 담아서 전달했다.

override func viewWillAppear(_ animated: Bool) {
	super.viewWillAppear(animated)
	firstTextField.text = ""
	secondTextField.text = ""
}

SecondViewController에서 돌아오면 이전에 입력했던 숫자가 없어지도록 하기 위해 viewWillAppear 메소드에 관련 코드를 추가했다.

두 번째 View Controller (SecondViewController.swift)

class SecondViewController: UIViewController {
    
    var result: String?
    
    @IBOutlet var resultLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if let result = result {
            resultLabel.text = result
        }
    }
    
    @IBAction func backButtonTapped(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

}

이전 view controller에서 받아온 계산 결과를 띄울 수 있도록 viewDidLoad 메소드에서 관련 코드를 작성했다.

profile
나의 내일은 파래 🐳

0개의 댓글