100 Days of SwiftUI

100 Days of SwiftUI - Day 19 项目1

2020-10-20  本文已影响0人  星星星宇

构建一个处理单位转换的应用程序:
用户将选择一个输入单位和一个输出单位,
然后输入一个值,
然后查看转换的输出。

你可以从以下选项选择一种

示例图

代码如下

struct ContentView: View {
    
    @State private var input = ""
    @State private var inputUnit = 0
    @State private var outPutUnit = 0
    var units = ["秒","分","小时","天"]

    var outPut: Double {
        let numberOfInput = Double(input) ?? 0
        var number秒 = 0.0
        
        let inputU = units[inputUnit]
        switch inputU {
        case "秒":
            number秒 = numberOfInput
        case "分":
            number秒 = numberOfInput * 60
        case "小时":
            number秒 = numberOfInput * 60 * 60
        case "天":
            number秒 = numberOfInput * 60 * 60 * 24
        default:
            number秒 = 0
        }
        
        var numberOutput = 0.0
        let outputU = units[outPutUnit]
        switch outputU {
        case "秒":
            numberOutput = number秒
        case "分":
            numberOutput = number秒 / 60
        case "小时":
            numberOutput = number秒 / 60 / 60
        case "天":
            numberOutput = number秒 / 60 / 60 / 24
        default:
            numberOutput = 0
        }
        return numberOutput
    }

    var body: some View {
        
        Form {
            Section {
                TextField("input", text: $input)
            }
            
            Section(header: Text("Select input unit")) {
                Picker("", selection: $inputUnit) {
                    ForEach(units.indices) {
                        Text("\(units[$0])")
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
            }
            
            Section(header: Text("Select onput unit")) {
                Picker("", selection: $outPutUnit) {
                    ForEach(units.indices) {
                        Text("\(units[$0])")
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
            }
            
            Section {
                Text("result: \(outPut)")
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读