본문 바로가기
💡 Today I Learned/개인 과제

[개인과제] 약식 계산기 만들기 - 스토리보드

by 솔비님 2024. 6. 27.

 

앱 개발 기초 강의 듣고 처음으로 간단한 계산기앱 만들기 개인 과제를 받았다

저번 팀 프로젝트 때 간단한 UI 만들기는 했었는데, 이번에는 조금 더 복잡한 단계들과 간략한 기능까지 구현해야함!

 

구현 단계 Level 1~8

 

  1. UILabel 로 숫자 라벨 띄우기
  2. Horizontal StackView : 버튼 4개를 모아 가로 정렬 스택 뷰 만들기
  3. Vertical StackView : Horizontal StackView 4줄을 세로로 정렬하는 스택 뷰 만들기
  4. 숫자 버튼과 연산 버튼의 색상 구분하기
  5. 버튼을 원형으로 만들기
  6. 버튼을 클릭하면 라벨에 표시되도록 하기
  7. 초기화 버튼 (AC) 구현
  8. 사칙연산 버튼 (=) 구현

01. 계산기 인터페이스 구현

 

 1️⃣ UILabel 로 계산된 값이 표시될 숫자 라벨 설정

      Constaints

      [Trailing/Leading_30] [Height_100] [Top_200]

      Design

      [Style Bold 30.0] [White]

 

 2️⃣ UIButton 1개 생성 후 아래와 같이 설정 후 3개 복사

      Constaints

      [Height/Width_80]

      Design

      [Style Bold 30.0] [White]

      [layer.cornerRadius_Number_40]

 

 3️⃣ 2번에서 생성한 UIButton 4개 묶어서

       Horizontal StackView 생성

       Constaints

      [Height/Width_350] [Fill Equally] [Spacing_30]

 

 4️⃣ 3번 복사해서 Vertical StackView 생성

       Constaints

      [Fill Equally] [Spacing_30]

      [Label Bottom으로부터 60] [Center X = Superview]

 

 5️⃣ UIButton 텍스트 변경 & 컬러 변경

 

 

 

 


02. ViewController 기능 구현

 

1️⃣ UILabel(numberBox)을 IBOutlet으로 연결하고 값이 담길 변수 선언

@IBOutlet weak var numberBox: UILabel!
var str = ""

 

 

2️⃣ 넘버 키패드와 사칙연산 키패드 IBAction 연결

     텍스트에 담긴 값을 1번에서 선언한 변수 str에 담아준 후 UILabel(numberBox)의 텍스트를 str의 값으로 업데이트

@IBAction func numPressed(_ sender: UIButton) {
    str.append(sender.currentTitle!)
    numberBox.text = str
}
    
@IBAction func operaterPressed(_ sender: UIButton) {
    str.append(sender.currentTitle!)
    numberBox.text = str
}

 

 

3️⃣ AC 클릭 시 값이 초기화 되도록 str을 0으로 

     업데이트된 값은 다시 UILabel(numberBox)에 담기도록 넣어줌

@IBAction func AcPressed(_ sender: UIButton) {
    str = "0"
    numberBox.text = str
}

 

 

4️⃣ 계산식 넣어주기

func calculate(expression: String) -> Int? {
	let expression = NSExpression(format: expression)
	if let result = expression.expressionValue(with: nil, context: nil) as? Int {
     	return result
	} else {
    	return nil
	}
}

 

 

5️⃣ = 클릭 시 동작할 수 있도록 4번에서 만든 계산식(Calculate) 을 result 값에 넣어주고

     result값을 다시 넘버박스에 넣어주는데 초기 result 값은 Int? 타입이므로 강제 언래핑 후 String으로 형변환 해줄 것

@IBAction func play(_ sender: UIButton) {
    let result = calculate(expression: str)
    numberBox.text = String(result!)
}

 


03. 작동 확인

 

   덧셈, 뺄셈, 곱셈, 나눗셈  ⭕️

   AC 초기화  ⭕️