개발/SWIFT 아이폰 / / 2023. 7. 19. 14:23

SwiftUI NavigationLink를 사용하여 데이터 전송

반응형

NavigationLink 첫 번째 화면에서 두 번째 화면으로

두 번째 화면에서 첫 번째 화면으로 데이터 전송

struct ContentView: View {
    @State var isLinkActive = false
    @State private var data: String = ""
    
    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                TextField("데이터 입력", text: $data)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                
                NavigationLink(destination: SecondView(data: $data, isLinkActive: $isLinkActive), isActive: $isLinkActive) {
                    Button(action: {
                        self.isLinkActive = true
                    }) {
                        Text("Login")
                            .font(.title)
                            .padding()
                            .foregroundColor(.white)
                            .background(Color.blue)
                            .cornerRadius(10)
                            .shadow(color: .gray, radius: 5, x: 0, y: 2)
                            .padding(.horizontal)
                    }
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white)
//            .edgesIgnoringSafeArea(.all)
        }
    }
}

struct SecondView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @Binding var data: String
    @Binding var isLinkActive: Bool
    @State private var newData: String = ""
    
    var body: some View {
        VStack {
            Text("두 번째 화면")
                .font(.title)
                .padding()
                .foregroundColor(.white)
                .background(Color.blue)
                .cornerRadius(10)
                .shadow(color: .gray, radius: 5, x: 0, y: 2)
                .padding(.horizontal)
            
            Text("전달된 데이터: \(data)")
                .foregroundColor(.gray)
            
            TextField("데이터 입력", text: $newData)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            
            Button(action: {
                // 데이터 업데이트 후 이전 화면으로 이동
                data = newData // 원하는 로직으로 데이터 업데이트
                
                // 이전화면 이동
                isLinkActive = false
                //presentationMode.wrappedValue.dismiss()
            }) {
                Text("첫 번째 뷰로 이동")
                    .font(.headline)
                    .foregroundColor(.white)
                    .padding()
                    .background(Color.green)
                    .cornerRadius(10)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
//        .edgesIgnoringSafeArea(.all)
//        .navigationBarBackButtonHidden(true)
    }
}
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유