ios - 使用文本字段输入 SwiftUI 阅读和计算

标签 ios swift swiftui

我想使用来自 2 个不同文本字段的输入进行计算,并将输出放在一个文本中。见代码:

@State var input1: String = ""

@State var input2: String = ""

var calculation : Double {
    let calculationProduct = Double(input1) * Double(input2)
    return calculationProduct
}

var body: some View {
VStack{
 TextField("", text: $input1)
 TextField("", text: $input1)

Text("\(calculation)")
}

问题是代码无法编译,我得到不同的编译错误,例如:“Binary operator '*' cannot be applied to two 'Double?'操作数”。

出了什么问题?

最佳答案

Double(input1) 返回 String? 因为它不能保证工作。例如双(“1abc”)

我们可以使用 guard letif let 甚至 nil 合并运算符 ?? 来处理这个问题。但对于下面的示例,我们将使用 guard let 优雅地处理它。

struct ContentView: View {
    @State var input1: String = ""
    @State var input2: String = ""

    var calculation : Double {
        guard let m = Double(input1), let n  = Double(input2) else { return 0 }
        return m * n
    }

    var body: some View {
        VStack {
            TextField("", text: $input1)
            TextField("", text: $input2)

            Text("\(calculation)")
        }
    }
}

编辑

根据您的评论,有多种方法可以在无效输入或小数点后两位的答案上显示“错误”。
对于这个例子,让我们在这两种情况下将 result 更改为计算的 String 属性,如下所示:

struct ContentView: View {
    @State var input1: String = ""
    @State var input2: String = ""

    var calculation: String {
        //check if both fields have text else no need for message
        guard input1.isEmpty == false, input2.isEmpty == false else { return "" }

        //check if both are numbers else we need to print "Error"
        guard let m = Double(input1), let n  = Double(input2) else { return "Error" }

        let product = m * n
        return String(format: "%.2f", product)
    }

    var body: some View {
        VStack {
            TextField("Enter First Number", text: $input1)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            TextField("Enter Second Number", text: $input2)
                .textFieldStyle(RoundedBorderTextFieldStyle())

            Text(calculation)
        }
    }
}

PS:如果你想确保只能输入数字,那么你应该考虑在 TextField 上应用 .keyboardType(.decimalPad) 修饰符。

关于ios - 使用文本字段输入 SwiftUI 阅读和计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61329716/

相关文章:

iphone - 在 MasterDetailview Xcode 4.2 中更改导航栏样式

ios - 向 itunesconnect 提交应用内购买总是被拒绝,因为它太旧了 productutil

iphone - 在 iOS/Objective-C 中干燥代码

swift - 在没有 segue 的情况下将数据传递给 Swift 中的 ViewController

ios - viewcontroller View 中导航项 titleView 的框架

ios - 类型 'ViewController' 不符合协议(protocol)

swiftui - 如何将 Color 绑定(bind)到 .fill()?

ios - 将错误从已部署的iOS应用程序返回给开发团队

callback - 向 SwiftUI Picker 添加回调

json - 如何在 Swift 中检查我的数组索引是否超出范围