如何将条件修饰符链接到所选值?

问题描述

我目前正在使用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 (将#修改为@)