【问题标题】:SwiftUI: How to pass a data from one view and use it in the viewModel of another viewSwiftUI:如何从一个视图传递数据并在另一个视图的 viewModel 中使用它
【发布时间】:2021-07-29 09:41:26
【问题描述】:

只是在视图之间传递数据并在视图模型中使用它。下面是用于传递电话号码的 FirstView 的代码:

struct FirstView: View {

    @State private var phone: String = "9876543210"
    @State private var isPresented: Bool = false

    var body: some View {
        ZStack {
            Color.background
            VStack {
                Spacer()
                TextField("type here...", text: $phone)
                   .onTapGesture {
                              isPresented.toggle()
                         }
                   .fullScreenCover(isPresented: $isPresented, content: {
                            SecondView(phone: phone)
                        })
                Spacer()
            }
        }
    }
}

如何使用从子视图模型中的主视图传递的电话数据作为文本字段的初始值?下面是 SecondView 的未完成代码:

struct SecondView: View {

    @StateObject private var viewModel = SecondViewModel()
    let phone: String // how to assign this obtained data in viewModel.phone?

    var body: some View {
        ZStack {
            Color.background
            VStack {
                Spacer()
                // textfield default text should be the phone number passed from FirstView
                TextField("type here...", text: $viewModel.phone)  
                Spacer()
            }
        }
    }
}

这是第二个视图模型:

final class SecondViewModel: ObservableObject {
    
    @Published var phone = ""
} 

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    使用initStateObject(wrappedValue:)。这是可能的解决方案。

    你的视图模型

    final class SubViewModel: ObservableObject {
        
        @Published var phone = ""
        
        init(phone: String) {
            self.phone = phone
        }
    }
    

    你的子视图

    struct SubView: View {
    
        @StateObject private var viewModel: SubViewModel
        private let phone: String
        
        init(phone: String) {
            self.phone = phone
            _viewModel = StateObject(wrappedValue: SubViewModel(phone: phone))
        }
    
        var body: some View {
            ZStack {
                Color.background
                VStack {
                    Spacer()
                    // textfield default text should be the phone number passed from main view
                    TextField("type here...", text: $viewModel.phone)
                    Spacer()
                }
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2022-11-29
      相关资源
      最近更新 更多