SwiftUI - 跨多个视图的小计 TextField 条目

SwiftUI - Subtotal TextField entries across multiple views

我有多个由 ForEACH 创建的视图。每个视图都有一个文本字段,用户可以在其中输入数字。我想小计每个视图中的每个条目。换句话说,小计每个视图中的绑定。

是我的做法不对吗?

ForEach(someArray.allCases, id: \.id) { item in
                    CustomeRowView(name: item.rawValue)
                }
struct CustomeRowView: View {
    
   
    var name: String
    @State private var amount: String = ""
    
    
    var body: some View {
        
        VStack {
            
            HStack {
                Label(name, systemImage: image)
 
                
                VStack {
                    TextField("Amount", text: $amount)
                        .frame(width: UIScreen.main.bounds.width / 7)
        
                    
                }

            }
         
        }
    }
 
}

如有任何帮助,我们将不胜感激。

有很多方法可以实现您的要求。我在这里提出一个非常 简单的方法,使用 ObservableObject 将信息保存在一个地方。 它具有add到信息字典fruits.

的功能

ContentView 中创建了一个 @StateObject 以保持单一的真实来源。 它使用 @ObservedObject 传递给 CustomeRowView 视图,并用于计数 当 return 键被按下时 TextField 的输入 (.onSubmit).

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class FruitCake: ObservableObject {
    @Published var fruits: [String : Int] = ["apples":0,"oranges":0,"bananas":0]
    
    // adjust for you purpose
    func add(to name: String, amount: Int) {
        if let k = fruits.keys.first(where: {[=10=] == name}),
           let sum = fruits[k] {
            fruits[k] = sum + amount
        }
    }
}
    
struct ContentView: View {
    @StateObject var fruitCake = FruitCake()
    
    var body: some View {
        VStack {
            ForEach(Array(fruitCake.fruits.keys), id: \.self) { item in
                CustomeRowView(name: item, fruitCake: fruitCake)
            }
        }
    }
}

struct CustomeRowView: View {
    let name: String
    @ObservedObject var fruitCake: FruitCake
    @State private var amount = 0
    
    var body: some View {
        HStack {
            Label(name, systemImage: "info")
            TextField("Amount", value: $amount, format: .number)
                .frame(width: UIScreen.main.bounds.width / 7)
                .border(.red)
                .onSubmit {
                    fruitCake.add(to: name, amount: amount)
                }
            // subtotal
            Text("\(fruitCake.fruits[name] ?? 0)")
        }
    }
    
}