我们先来简单阐述一下我们这个支票拆分app的几个功能。
- 用户能够输入支票金额
- 输入人数来平摊这个支票
- 以及客户想要留下多少小费给服务员(当然这个在中国一般不存在的哦)
货币的代码:
1.CNY—人名币
2.USD—美元
3.EUR—欧元
4.JPY— 日元
1.TextField
Textfield(“提示用户”,Value:$用户双向绑定的值,获取当前用户所在区域的货币代码)
@State,经过属性包装器,包装的值当值发生改变时候它会重新加载UI来响应这些改变
获取当前用户所使用的货币: format: .currency(Local.current.currency ?? “USD”)
获取用户所在区域的货币代码,如果没有就设置为美元
2.keyboardType(),
数字键盘:.numberPad .decimaIpad
这两个键盘的唯一区别:
(.number)只有数字键盘但没有小数点
下面这个是.decimaIpad
OK,完成上面两部之后,我们来看看我们现在所拥有的具体代码是什么样的?
import SwiftUI
struct ContentView: View {
@State var InputValue=0.0
@State var numberOfPeole=0
let tipPercenteage=[0,10,15,20,30]
@State var selectTip=0
var body: some View {
NavigationView{
Form{
Section{
TextField("请输入支票金额",value: $InputValue,format:.currency(code:Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
Picker("select peple number",selection: $numberOfPeole){
ForEach(2..<100){
Text("\($0) peole")
}
}
}
Section{
Text(InputValue,format:.currency(code:Locale.current.currencyCode ?? "USD"))
}
}
.navigationTitle(Text("Main Screen"))
}
}
}
3.picker选择器
“That counts from 2 up to 100, creating rows. What that means is that our 0th row – the first that is created – contains “2 People”, so when we gave numberOfPeople the value of 2 we were actually setting it to the third row, which is “4 People”.”
我们现在已经有一个TextFiled供用户来输入支票的金额,和一个用来显示金额数的格式文本Text。我们再在这两个控件之间增加一个picker选择器,供用户来选择分担这张支票的人数。
@State var numberOfPeole=2
Picker("select peple number",selection: $numberOfPeole){
ForEach(2..<100){
Text("\($0) peole")
4.最后把成品放上来吧,需要的可以直接把它放到Xcode直接运行一下。这里面有一些变量的命名不太好。
struct ContentView: View {
@State var InputValue=0.0
@State var numberOfPeole=0
let tipPercenteage=[0,10,15,20,30]
@State var selectTip=0
var totalPerson:Double{
let peopleCount=Double(numberOfPeole+2)
let tipSelection=Double(selectTip)
let tipValue=InputValue/100*tipSelection
let grandTotal = InputValue+tipValue
let amountPerson=grandTotal/peopleCount
return amountPerson
}
var body: some View {
NavigationView{
Form{
Section{
TextField("请输入支票金额",value: $InputValue,format:.currency(code:Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
Picker("select peple number",selection: $numberOfPeole){
ForEach(2..<100){
Text("\($0) peole")
}
}
}
Section{
Picker("tip",selection: self.$selectTip){
ForEach(tipPercenteage,id: \.self){
Text($0,format: .percent)
}
}.pickerStyle(.segmented)
} header: {
Text("How much tip do you want to leave?")
}
Section{
Text(totalPerson,format:.currency(code:Locale.current.currencyCode ?? "USD"))
![在这里插入图片描述](https://img-blog.csdnimg.cn/65fec5cb1e044ef094a9caeca06af4e8.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBASnVuZSBBSQ==,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
}
}
.navigationTitle(Text("Main Screen"))
}
}
}