Swift TIL(68)- textFieldShouldReturn 타입에서의 Bool 리턴(리턴키 default behavior 알아보기)

웰디(Well-D)·2023년 11월 3일
0

Sweet & Soft, SWIFT

목록 보기
67/76

앱 만들기 bmi 앱 계속
본격적으로 앱을 만들었음

UI를 구성, 직접세그웨이 방식으로 화면전환 후 데이터전달구현

오늘 내가 고민하고 정리해본것들을 간단히 적는다.

해당 코드

코드의 목적 : 앱 키보드의 엔터(리턴) 버튼을 누를때 다음 텍스트필드로 넘어가기, 모든 텍스트필드가 다 차있다면 키보드 내리기
textFieldShouldReturn (이미 구현되어있는) 메서드 사용

// 버튼을 누르면 다음 텍스트필드로 넘어가도록
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 두개의 텍스트필드를 모두 종료
        if heightTextField.text != "", weightTextField.text != "" {
            // 두 텍스트필드 모두 빈 문자열이 아니라면(입력되어있다면)
            textField.resignFirstResponder()
            // textField를 응답객체에서 해제하겠다
            return true // 엔터입력을 허락한다
            
            // 두번째 텍스트필드로 넘어가도록
        } else if heightTextField.text != "" {
            // (둘다입력된게 아닌상태에서) heightTextField가 빈문자열이 아니라면(입력되어있다면)
            weightTextField.becomeFirstResponder()
            // weightTextField를 응답객체로 사용하겠다
            return true // 엔터입력을 허락한다
            
        } else  {
            heightTextField.becomeFirstResponder()
            return true // 엔터입력을 허락한다
        }
    }

나의 의문

return false 와 return true 동작의 차이가 없어보였음

공식문서를 보았다.

resignFirstResponder()

Notifies this object that it has been asked to relinquish its status as first responder in its window.
func resignFirstResponder() -> [Bool](https://developer.apple.com/documentation/swift/bool)

textFieldShouldReturn(_:)

Asks the delegate whether to process the pressing of the Return button for the text field.
optional func textFieldShouldReturn(_ textField: [UITextField](https://developer.apple.com/documentation/uikit/uitextfield)) -> [Bool](https://developer.apple.com/documentation/swift/bool)

Return Value

true if the text field should implement its default behavior for the return button; otherwise, false.

Discussion

The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped. For example, if you want to dismiss the keyboard when the user taps the return button, your implementation can call the [resignFirstResponder()](https://developer.apple.com/documentation/uikit/uiresponder/1621097-resignfirstresponder) method.

여기서 얻을 수 있는 것

Return Value 에 대한 설명을 보면 리턴키의 default behavior 과 관련이 있음을 알 수 있다.
나는 이 default behavior 가 뭔지 궁금해서 코드로 실험해 보았다.

결론

다음과 같은 차이가 있다.

별거아니지만 소소한 궁금증이었다.

참고

참고로 공식문서를 보면서 resignFirstResponder() 과 becomeFirstResponder() 자체가 Bool 타입을 반환하고 (default 로 true 를 반환한다고 한다) 있다는 내용을 보고 다음과 같은 코드로 실험해보았는데
(실제 리턴키의 default behavior 실행 여부는 확인이 어려웠지만)

일단 동작에는 무리가 없다 (textFieldSouldReturn 의 리턴타입인 Bool 에 충족한다는 뜻 정도로 해석했다)

위에서 설명한 방식으로 함수의 리턴타입을 다시 return 한 코드

// 버튼을 누르면 다음 텍스트필드로 넘어가도록
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 두개의 텍스트필드를 모두 종료
        if heightTextField.text != "", weightTextField.text != "" {
            // 두 텍스트필드 모두 빈 문자열이 아니라면(입력되어있다면)
            return textField.resignFirstResponder()
            // textField를 응답객체에서 해제하겠다
            // return true // 엔터입력을 허락한다
            
            // 두번째 텍스트필드로 넘어가도록
        } else if heightTextField.text != "" {
            // (둘다입력된게 아닌상태에서) heightTextField가 빈문자열이 아니라면(입력되어있다면)
            return weightTextField.becomeFirstResponder()
            // weightTextField를 응답객체로 사용하겠다
            // return true // 엔터입력을 허락한다
            
        } else  {
            return heightTextField.becomeFirstResponder()
            // return true // 엔터입력을 허락한다
        }
    }

계속 배우는 단계이니 혹시 저의 해석이 잘못되었거나 추가, 다른 의견이 있으시다면 언제든 댓글 부탁드립니다!

profile
Wellness 잘사는 것에 진심인 웰디입니다. 여러분의 몸과 마음, 통장의 건강을 수호하고싶어요. 느리더라도, 꾸준히

0개의 댓글