SwiftUI-使用var或let从两个文本字段中添加值

锦葵

如何在SwiftUI中添加两个文本字段的值?

我有以下代码:

import SwiftUI

struct ContentView: View {
    
    @State private var value1 = ""
    @State private var value2 = ""
    
    private var sumValues = (Int(value1) ?? 0) + (Int(value2) ?? 0)
    
    var body: some View {
        VStack {
            TextField("type value 1 here", text: $value1)
                .keyboardType(.numberPad)
            
            TextField("type value 2 here", text: $value2)
                .keyboardType(.numberPad)
            
            Text("sum: \(sumValues)")
            
            // I need to have a var or let, so I cannot use something like this:
            //Text("sum: \((Int(value1) ?? 0) + (Int(value2) ?? 0))")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

我正在与私有var sumValues ...一起出现此错误

无法在属性初始化程序中使用实例成员'value1';属性初始化程序在“自我”可用之前运行

无法在属性初始化程序中使用实例成员“ value2”;属性初始化程序在“自我”可用之前运行

科学怪人

使用computed-property

private var sumValues: Int { (Int(value1) ?? 0) + (Int(value2) ?? 0) }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章