構(gòu)建一個處理單位轉(zhuǎn)換的應(yīng)用程序:
用戶將選擇一個輸入單位和一個輸出單位怪与,
然后輸入一個值先紫,
然后查看轉(zhuǎn)換的輸出石抡。
你可以從以下選項選擇一種
- 溫度轉(zhuǎn)換:用戶選擇攝氏度枯芬,華氏度或開氏度维苔。
- 長度轉(zhuǎn)換:用戶選擇米碰辅,公里,英尺介时,碼或英里没宾。
- 時間轉(zhuǎn)換:用戶選擇秒,分鐘沸柔,小時或天循衰。
- 體積轉(zhuǎn)換:用戶選擇毫升,升褐澎,杯会钝,品脫或加侖。
示例圖
代碼如下
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)")
}
}
}
}