본문 바로가기
TIL(Today I Learned)

2024.06.28 Today I Learned

by 승환파크 2024. 6. 28.

오늘은 Swift Storyboard로 계산기를 만드는 과제를 하는 도중 에러가 발생한 것에 대해 적어볼 것이다.

 

currentText VS titleLabel?.text

storyboard로 버튼을 만들고 버튼 안에 있는 텍스트를 currentText 로 가져오려 하니 자꾸만 nil 값이 반환되어서 값을 가져올 수 없었다.

거이 1시간 가량 붙잡고 ChatGPT 에게도 물어보고 어떻게든 찾아보려고 노력하다 겨우 찾아냈는데 바로 버튼의 Style 문제에서 발생한 것이다.

 

윈래는 왼쪽 상태에서 currentText 로 데이터를 가져오려 하니 에러가 발생해서 titleLable?.text 로 언래핑을 통해 가져왔는데 더 간단하게 currentText로 사용하고 싶어서 방법을 찾아보니 Style 을 Default 로 변경해주면 이상하게 값이 잘 나오는 것이다...

 

아직까지는 이유를 찾지 못했지만 나중에 찾으면 추가할 예정이다... 아무튼... 버튼 생성하면 Default 로 수정하기....

@IBAction func numberButton(_ sender: UIButton) {
    if let str = textLabel.text, let text = sender.titleLabel?.text {
        if let num = Int(str), num == 0 {
            textLabel.text = text
        } else {
            textLabel.text = calculator.removeZero(str + text)
        }
    }
}

위의 코드에서 아래의 코드로 수정하였다.

@IBAction func numberButton(_ sender: UIButton) {
    if let str = textLabel.text, let text = sender.currentTitle {
        if let num = Int(str), num == 0 {
            textLabel.text = text
        } else {
            textLabel.text = calculator.removeZero(str + text)
        }
    }
}

'TIL(Today I Learned)' 카테고리의 다른 글

2024.07.04 Today I Learned  (0) 2024.07.05
2024.07.01 Today I Learned  (0) 2024.07.01
2024.06.27 Today I Learned  (0) 2024.06.27
2024.06.26 Today I Learned  (0) 2024.06.26
2024.06.24 Today I Learned  (1) 2024.06.24