TextField가 들어간 alert 만들려고 했는데…

SteadySlower·2022년 8월 26일
0

SwiftUI의 alert에 TextField 추가?

이번에 iOS에서 단어장을 추가할 수 있는 기능을 만들면서 Alert를 사용해보려고 했습니다. 그래서 아래와 같은 코드를 짰습니다.

.alert("단어장 추가", isPresented: $showAlert, actions: {
    TextField("새로운 단어장 이름", text: $viewModel.newName)
    Button("추가", action: { viewModel.addWordBook() })
    Button("취소", role: .cancel, action: {})
}, message: {
    Text("새로운 단어장을 추가합니다.")
})

하지만 결과는 아래와 같았습니다.

🚫 alert의 action에는 Button, message에는 Text만 가능하다

iOS 15의 alert는 아직 위에 언급한 것 이외의 다른 View를 허용하지 않는다고 합니다. 하지만 iOS 16에서는 다른 TextField와 SecureTextField를 허용할 예정이라고 합니다.

(참고) UIKit 에서는?

참고로 UIKit에서는 아래와 같은 코드로 UIAlertController에 텍스트 필드를 추가 했었습니다.

lazy var addWordbookAlert: UIAlertController = {
    let alert = UIAlertController(title: "단어장 추가", message: nil, preferredStyle: .alert)
    //✅ TextField를 추가하기
		alert.addTextField { tf in
        tf.placeholder = "추가할 단어장 이름"
    }
    let register = UIAlertAction(title: "추가", style: .default) { }
    let cancel = UIAlertAction(title: "취소", style: .cancel, handler: nil)
    alert.addAction(register)
    alert.addAction(cancel)
    return alert
}()
profile
백과사전 보다 항해일지(혹은 표류일지)를 지향합니다.

0개의 댓글