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

你选择哪种单位取决于你,但是你可以选择以下单位之一:

  • 温度转换:用户选择摄氏度,华氏度或开氏度。
  • 长度转换:用户选择米,公里,英尺,码或英里。
  • 时间转换:用户选择秒,分钟,小时或天。
  • 体积转换:用户选择毫升,升,杯,品脱或加仑。

如果要进行长度转换,则可能有:
输入单位的米,千米,英尺,码或英里的分段控件。
第二个分段控件,用于输出单位的米,公里,英尺,码或英里。
用户在其中输入数字的文本字段。
文本视图,显示转换结果。
因此,如果选择米作为源单位,将英尺作为输出单位,然后输入10,则将看到32.81作为输出。

下面这两个确实有点难记。写代码的时候又忘了。

滑块Picker

.pickerStyle(SegmentedPickerStyle())

保留两位小数

Text("$ \(finalmon, specifier: "%.2f")")

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// ContentView.swift
// Practise2-2
//
// Created by 张洪Hoo on 2020/3/29.
// Copyright © 2020 张洪Hoo. All rights reserved.
//

import SwiftUI

struct ContentView: View {
@State private var beforenum = ""
@State private var beforeUnit = 1
// @State private var afternum: Double = 0
@State private var afterunit = 0


var afternum: Double {
let beforenum = Double(self.beforenum) ?? 0
let beforeUnit = self.beforeUnit
let afterunit = self.afterunit

var num: Double

switch beforeUnit {
case 0:
num = beforenum
case 1:
num = beforenum * 1.8
num = num + 32
default:
num = beforenum * 0.5555556
}

switch afterunit {
case 0:
return num

case 1:
num = num - 32
num = num / 1.8
return num
default:
num = num / 0.5555556
return num
}
}

let unit = ["华氏度","摄氏度","开氏度"]

var body: some View {
NavigationView {
Form {
TextField("转换前的数值", text: $beforenum)
.keyboardType(.numberPad)

Picker(selection: $beforeUnit, label: Text("选择起始单位")) {
ForEach(0 ..< self.unit.count) { item in
Text(self.unit[item])
}

}
.pickerStyle(SegmentedPickerStyle())

Section {
Text("\(self.afternum, specifier: "%.2f")")
Picker(selection: $afterunit, label: Text("选择目标单位")) {
ForEach(0 ..< self.unit.count) { item in
Text(self.unit[item])
}
}
}
.pickerStyle(SegmentedPickerStyle())

}
.navigationBarTitle(Text("单位转换"))
}
}
}

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

1792

这次写了个其他的转换。

SwiftPlayground 进度

1792