首页 > 解决方案 > SWIFTUI:当我有初始化声明时,使用环境演示模型关闭按钮单击视图

问题描述

所以我想这样做,简单的事情是使用@Environment(.presentationMode) varpresentationMode。但是我的视图中有 INIT() 声明,我不知道如何将 Environment var 放入其中,以便在正文视图中使用它。

有可能使用它吗?以及如何在 init func 中声明它?

我的初始化:

     var model: ResponseModel
   @State var operacion: String
    @State var cliente: String
    @State var usd = ""
@State var ars = ""
@State var tasa = ""
    @State var idd = ""
    

    
    init(model: ResponseModel) {
        self.model = model
        self.operacion = model.operacion ?? ""
        self.usd = model.usd ?? ""
        self.ars = model.ars ?? ""
        self.tasa = model.tasa ?? ""
        self.cliente = model.cliente ?? ""
        self.idd = model.id ?? ""
       
        
        }

如果我不将环境变量放入 init 声明中,我将遇到构建错误

谢谢

标签: swiftxcodeenvironmentinit

解决方案


您必须在使用 self 之前进行operacion初始化。cliente

您可以像使用其他状态属性一样执行此操作。像这样:

@State var operacion: String = ""

但是如果要在init中改变值,最好使用下面的方法。

或者您在 init.xml 中初始化这些变量。由于它们是propertyWrappers,所以看起来很特别,如下所示:

init(model: ResponseModel) {
    self.model = model
    self._operacion = State(wrappedValue: model.operacion ?? "")
    // ...

这是一个完整的工作示例:

struct Test: View {
    @Environment(\.presentationMode) var presentationMode
    
    var model: ResponseModel
    
    @State var operacion: String
    @State var cliente: String
    @State var usd: String
    @State var ars: String
    @State var tasa: String
    @State var idd: String
    
    init(model: ResponseModel) {
        self.model = model
        _operacion = State(wrappedValue: model.operacion ?? "")
        _cliente = State(wrappedValue: model.cliente ?? "")
        _usd = State(wrappedValue: model.usd ?? "")
        _ars = State(wrappedValue: model.ars ?? "")
        _tasa = State(wrappedValue: model.tasa ?? "")
        _idd = State(wrappedValue: model.id ?? "")
    }
    
    var body: some View {
        Text("Hallo World")
    }
}

推荐阅读