如何解决如何将条件修饰符链接到所选值?
我目前正在使用Swift进行100天的Swift黑客攻击,并且对以下问题有些困惑。
我正在尝试使用条件修饰符来更改前景色,具体取决于用户选择的笔尖是否为0%,但是几个小时后,我努力尝试将@State从false更改为true(如果已选择笔尖) 0%。
我认为这可能是一个理解问题,因为我一直在尝试是否产生与视图不一致的错误的语句,所以我想知道是否应该在此处使用视图修饰符/自定义视图来代替,也许我只是不理解这是课程材料的一部分。
下面的代码:
import SwiftUI
struct ContentView: View {
@State private var restaurantBill = ""
@State private var diners = 2
@State private var selectedTip = 2
let tipAmount = [5,10,15,20,25,0]
@State private var noTipSelected = false // <-- no tip selected state is equal to false
// computed properties
var totalPerPerson: Double {
let peopletoCount = Double(diners + 2)
let tipSelection = Double(tipAmount[selectedTip])
let orderAmount = Double(restaurantBill) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = tipValue + orderAmount
let costPerPerson = grandTotal / peopletoCount
return costPerPerson
}
var totaloverall: Double {
let tipSelection = Double(tipAmount[selectedTip])
let orderAmount = Double(restaurantBill) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = tipValue + orderAmount
return grandTotal
}
var body: some View {
NavigationView {
Form {
Section {
TextField("£ total bill amount",text: $restaurantBill)
.keyboardType(.numberPad)
}
Picker("Table for: ",selection: $diners){
ForEach(2..<100){
Text("\($0) diners")
}
}
Picker("Select Tip: ",selection: $selectedTip){
ForEach(0..<tipAmount.count){
Text("\(self.tipAmount[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle())
Section {
Text("Total bill is: £\(totaloverall,specifier: "%.2f")")
.foregroundColor(noTipSelected ? .green : .red) //<---- my conditional modifier
}
Section {
Text("Each diner pays: £\(totalPerPerson,specifier: "%.2f")")
}
}
.navigationBarTitle("WeSplit v2.0")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
任何想法表示赞赏。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。