Standard Mission
TextField로 데이터 입력받아 Life Cycle 활용해 다른 View에 데이터 전달해보기
(실습 내용에 이어서 사칙연산 등 다양한 계산 활용해보기)
✅ 화면 전환 구현
✅ Life Cycle 활용해 다른 View에 데이터 전달
UILabel
: 타이틀 부분, 계산 결과 부분UIImageView
: 곰인형 이미지UITextField
: 숫자 입력 부분UIButton
: 사칙연산 버튼, 다시 할래요 버튼@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)
}
사칙연산 결과를 계산하는 부분과 화면 전환하는 부분이 중복되는 것 같아서 각각 calculate
와 presentSecondViewController
라는 메소드를 만들어서 분리했다.
계산 결과 문장(0 + 0 = 0 입니다) 전체를 SecondViewController의 result
프로퍼티에 담아서 전달했다.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
firstTextField.text = ""
secondTextField.text = ""
}
SecondViewController에서 돌아오면 이전에 입력했던 숫자가 없어지도록 하기 위해 viewWillAppear
메소드에 관련 코드를 추가했다.
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
메소드에서 관련 코드를 작성했다.