SwiftUI 에서 TextInput 이 있는 Alert 를 띄워주기

반응형

목적: SwiftUI 에서 TextInput 이 있는 Alert 를 띄워주기 위함.

 

결론:

기본적으로 아직까지는 SwiftUI 에서 커스텀 팝업을 만들려면 아래 링크에 소개된 방법 외에는 어려워보인다.

하지만 목적에 언급된 TextInput 이 있는 Alert 의 경우는 다음과 같이 하면 된다.

 

struct ContentView: View {
    @State private var presentAlert = false
    @State private var username: String = ""
    @State private var password: String = ""
    
    var body: some View {
        Button("Show Alert") {
            presentAlert = true            
        }
        .alert("Login", isPresented: $presentAlert, actions: {
            TextField("Username", text: $username)

            SecureField("Password", text: $password)

            
            Button("Login", action: {})
            Button("Cancel", role: .cancel, action: {})
        }, message: {
            Text("Please enter your username and password.")
        })
    }
}

 

ChatGPT 가 알려준 Alert 의 message 부분에 View 를 넣어서 만드는 방식은 최신버전에는 안된다.

ChatGPT 에 다음과 같이 질문하니 코드를 생성해주었다. 하지만 실제 적용해보니 message 부분에 커스텀 View 를 넣어줄 수 없도록 되어 있었다. 아마 버전이 바뀌면서 달라진 것 같다.

"FullScreenCover 로 opacity 를 주고 텍스트인풋이 있는 Alert 코드 좀 만들어주세요."
SwiftUI의 기본 Alert는 텍스트 입력을 직접 지원하지 않습니다. 그러나 @State와 다른 뷰들을 활용하여 커스텀 모달을 만들어 이 기능을 구현할 수 있습니다.
 
다음은 텍스트 입력이 있는 커스텀 알림을 만드는 방법을 보여주는 예제입니다:
 
이 예제에서는 alert 수식어를 사용하여 알림을 표시하며, customMessageView 함수를 사용하여 텍스트 입력 필드를 포함한 사용자 정의 메시지 뷰를 반환합니다.
 
import SwiftUI

struct ContentView: View {
    @State private var showAlert: Bool = false
    @State private var inputText: String = ""

    var body: some View {
        VStack {
            Button("Show Alert") {
                showAlert.toggle()
            }
        }
        .alert(isPresented: $showAlert, content: {
            Alert(title: Text("Enter Text"), message: customMessageView(), primaryButton: .default(Text("OK"), action: {
                print("Text entered: \(inputText)")
                showAlert = false
            }), secondaryButton: .cancel())
        })
    }

    @ViewBuilder
    private func customMessageView() -> some View {
        VStack {
            Text("Please input text below:")
            TextField("", text: $inputText)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(maxWidth: 200)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
 

 

다음의 글을 참고하면 SwiftUI 에서 커스텀 팝업을 사용할 수 있게 해준다. 기본적으로 SwiftUI 에서는 .sheet , .popover , .fullScreenCover , .alert , .confirmationDialog 등등 을 사용할 수 있는데 이것으로는 커스텀 팝업을 아래의 UIKit 과 같이 만들어 줄 수가 없다. 아직 modalPresentationStyle 과 modalTransitionStyle 을 지정하는 기능이 없는듯 보인다.

https://michaziobro-21492.medium.com/swiftui-missing-modal-presentation-view-modifier-98f00228c0b6

 

UIKit 에서 새로운 뷰컨트롤러를 띄워줄 때 스타일을 지정해줄 수 있다. 그리고 새로운 뷰컨트롤러 (팝업용 뷰컨트롤러) 를 오토레이아웃을 사용하여 적절한 크기로 만들고 배경을 투명하게 하면 overCurrentContext 를 사용하여 띄워주었을 경우 커스텀 팝업이 된다.

 

modalPresentationStyle
modalPresentationStyle is an enumeration that defines the way the presented view controller is displayed on the screen. There are several values you can choose from, including:

fullScreen: The presented view controller covers the entire screen.
pageSheet: The presented view controller covers the screen and the navigation bar is translucent.
formSheet: The presented view controller is displayed as a form-sized modal view.
currentContext: The presented view controller inherits the presentation context of the presenting view controller.
overFullScreen: The presented view controller covers the entire screen and is displayed over the status bar.
overCurrentContext: The presented view controller is displayed over the current context.

 

 

반응형

'MAC & iOS' 카테고리의 다른 글

opaque type  (0) 2023.09.18
ios Networking  (0) 2023.09.15
풀다운버튼, 팝업버튼 - ios / 옵션메뉴, 컨텍스트 메뉴, 팝업메뉴 - aos  (0) 2023.09.15
Clean Architecture using SwiftUI  (0) 2023.09.13
iOS 앱 소유권 이전  (1) 2023.07.20

댓글

Designed by JB FACTORY