Today I Learn

Today I Learn: UIAlertController에 TextField 추가 및 데이터 사용

Goniii 2025. 3. 7. 19:28

 

오늘은 Alert에 TextField를 추가하는 방법을 알아보려고 한다.

생각보다 아주 간단하다

Alert에 TextField를 추가하기 전 Alert을 생성하는 방법에 대해 알아보자

 

 

https://developer.apple.com/documentation/uikit/uialertcontroller

 

UIAlertController | Apple Developer Documentation

An object that displays an alert message.

developer.apple.com

 

  • 우리가 아는 알림을 띄우는 컨트롤러이다

 

 

Alert 생성하기

  • 가장 기본적인 확인 버튼, 취소 버튼으로 구성된 Alert을 생성해보겠다
    @objc private func createAlert() {
        let alert = UIAlertController(title: "Alert", message: "Password Alert", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "cancel", style: .destructive)
        let confirmAction = UIAlertAction(title: "confirm", style: .default)
        
        alert.addAction(cancelAction)
        alert.addAction(confirmAction)
        
        self.present(alert, animated: true, completion: nil)
    }

 

 

 

해당 Alert에 TextField를 추가하는 방법은 아주 간단하다!

바로 UIAlertController의 addTextField() 메서드를 사용해주면 끝!

https://developer.apple.com/documentation/uikit/uialertcontroller/addtextfield(configurationhandler:)

기존 코드에서 추가 후 차이를 보면

 

Alert에 TextField 추가

    @objc private func createAlert() {
        let alert = UIAlertController(title: "Alert", message: "Password Alert", preferredStyle: .alert)
        
        // TextField 추가
        alert.addTextField()
        
        let cancelAction = UIAlertAction(title: "cancel", style: .destructive)
        let confirmAction = UIAlertAction(title: "confirm", style: .default)
        
        alert.addAction(cancelAction)
        alert.addAction(confirmAction)
        
        self.present(alert, animated: true, completion: nil)
    }

 

alert.addTextField() 한 줄 추가했다고 바로 생겨버렸다 생각보다 아주 간단했다

 

Alert 내부 TextField 속성 정의

그러면 해당하는 텍스트 필드는 어떻게 꾸밀까?

공식 문서에서 보듯 addTextField 메서드는 configurationHandler를 제공한다 이 핸들러를 통해 textField 값을 받아 프로퍼티를 설정할 수 있다

        // TextField 추가
        alert.addTextField { textField in
            textField.placeholder = "placeholder"
            textField.textColor = .red
        }

 

 

 

 

Alert 내부 TextField - text 값 사용

그러나 추가한 TextField로 입력 받은 값을 처리할 수 있어야 한다

어디서 활용할 수 있을까??  언제 필요할까??

바로 confirm 버튼을 눌렀을 때 textField의 text 값이 필요하다

그럼 어디서 설정할까?

우리가 Confirm 이라는 alertAction을 생성해서 UIAlertController에 추가했다

https://developer.apple.com/documentation/uikit/uialertaction

 

UIAlertAction | Apple Developer Documentation

An action that can be taken when the user taps a button in an alert.

developer.apple.com

 

 

 

UIAlertAction의 생성자에는 UIAlertAction을 사용할 수 있는 handler를 제공한다 이 기능을 사용하면 된다

Cancel 버튼에서는 사용할 수 없고 confirm 버튼을 눌렀을 때만 사용가능해진다

        // alerAction은 사용하지 않으니 _ 처리
        let confirmAction = UIAlertAction(title: "confirm", style: .default) { _ in
            guard let textField = alert.textFields?.first else { return }
            print(textField.text ?? "textField nil")
        }