我想更新和使用picker、textfield和get price函数中的容器成员.

struct PropertyContainer: Equatable {
    static func == (lhs: PropertyContainer, rhs: PropertyContainer) -> Bool {
        return lhs.fromQty == rhs.fromQty && lhs.fromCurrency == rhs.fromCurrency && lhs.toCurrency == rhs.toCurrency && lhs.toQty == rhs.toQty
    }
    @State var toQty: Double = 1.0
    @State var toCurrency: String = "ETH"
    @State var fromQty: Double = 1.0
    @State var fromCurrency: String = "BTC"
}

struct ContentView: View {
@State private var propertyContainer = PropertyContainer()

在文本字段和 Select 器中使用容器的成员

.task(id: propertyContainer) {
            do {
                price = try await listMaker.getPrice(fromCurrency: propertyContainer.fromCurrency, fromQty: propertyContainer.fromQty, toCurrency: propertyContainer.toCurrency, toQty: propertyContainer.toQty, type: "Fixed")
                print(propertyContainer.fromCurrency)
            } catch {
                print("Error")
            }
        }

推荐答案

由于所有函数调用都是相同的,您可以通过一些重构来完成:

  1. 创建一个包含所有要响应的属性的 struct (注意:由于您没有提供属性,例如toQty…这将是一个通用示例):

    struct PropertyContainer: Equatable{ //important to conform to Equatable
        var property1: Bool = true
        var property2: Bool = true
        // and so on....
    }
    
  2. 创建在视图中保存属性的@State变量:

    @State private var propertyContainer = PropertyContainer()
    
  3. 按如下方式创建任务:

    .task(id: propertyContainer) {
     do {
     price =
         try await listMaker.getPrice(fromCurrency: fromCurrency, fromQty: fromQty, toCurrency: toCurrency, toQty: toQty, type: "Fixed")
       } catch {
       print("Error")
       }
    }
    

现在只能通过容器propertyContainer访问(读写)您的属性,例如:

Button {
    propertyContainer.property1.toggle()
} label: {
    Text("label")
}

当您更改容器中的属性时,整个 struct 都会更改,任务也会执行.

编辑:

Picker的示例:

Picker("", selection: $propertyContainer.selected) {//beware the $ for the binding
    ForEach(selectable) { selection in
        Text(selection)
    }
}

Swift相关问答推荐

SwiftUI—如何识别单词并获取视觉中的位置

为SwiftUI文本视图提供固定宽度,并仅在文本换行时使文本视图底部增大

在按下按钮动画后执行按钮动作

是否可以循环遍历SWIFT子类并访问它们的静态变量S?

在MacOS上检测键盘是否有Globe键

SwiftData/PersistentModel.swft:540:致命错误:不支持的关系密钥路径ReferenceWritableKeyPath

如何在 Vapor 中制作可选的查询过滤器

Swift iOS:确定贝塞尔曲线路径是否与 UIView 框架相交?

如何在 swift 5.0 中获取当前行

Swift Combine:如何在保留发布者结果顺序的同时进行收集?

Swiftui 按钮依次显示一组图像

如何在 SwiftUI 中将图像传递到 2 个视图

Swift-如何接受多个(联合)类型作为参数

试图同时实现两个混合过渡

使用 swift 运行 pod install 时出错

FCM 后台通知在 iOS 中不起作用

自定义 MKAnnotation 标注视图?

用 UIBezierPath 画一条线

Void 函数中意外的非 Void 返回值 (Swift 2.0)

在 Swift 中从服务器播放视频文件