오늘은 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() 메서드를 사용해주면 끝!
기존 코드에서 추가 후 차이를 보면
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")
}
'Today I Learn' 카테고리의 다른 글
Today I Learn: Swift에서의 연결 리스트 (0) | 2025.03.11 |
---|---|
Today I Learn - 숫자 야구 게임(Set VS Array) (0) | 2025.03.10 |
Today I Learn: UILabel 내부 Padding 설정하기 (0) | 2025.03.06 |
Today I Learn (4) : UIButton.AddTarget 데이터 전달 문제 리팩토링 (0) | 2025.03.05 |
Today I Learn(3): 동적으로 뷰 추가 및 삭제 (1) | 2025.03.05 |