【问题标题】:How to change the var when selecting specific value on the Picker (SwiftUI)在选择器(SwiftUI)上选择特定值时如何更改 var
【发布时间】:2020-03-31 13:27:50
【问题描述】:

在 UI 选择器中选择 0% 时,我需要将 useRed 值更改为 true(或 tipPercentage 变为 4)。

我尝试了以下方法,但出现警告“在视图更新期间修改状态,这将导致未定义的行为”,并且 useRed 值仍然是 false:

import SwiftUI

struct ContentView: View {


    @State private var tipPercentage = 2
    @State private var useRed = false

    let tipPercentages = [10, 15, 20, 25, 0]

    var redCheck: Bool {
        if tipPercentage == 4 {
            useRed = true
        } else { useRed = false }
        return useRed
    }


    var body: some View {

        NavigationView {
            Form {

                Section (header: Text("How much tips do you weant to leave?")){
                    Picker("Tip percentage", selection:
                    $tipPercentage) {
                        ForEach(0 ..< tipPercentages.count) {
                            Text("\(self.tipPercentages[$0])%")
                        }

                        }
                      .pickerStyle(SegmentedPickerStyle())
                }.foregroundColor(redCheck ? .red : .black)

            }
        }
    }

【问题讨论】:

    标签: ios swift uipickerview swiftui


    【解决方案1】:

    你可以使用一个函数来设置颜色:

    func updateColor() -> Color {
        if tipPercentage == 4 {
            return .red
        } else {
            return .black
        }
    }
    

    现在你可以像这样使用它了:

    .foregroundColor(self.updateColor())
    

    现在您不需要 redCheck 变量了。

    【讨论】:

      【解决方案2】:

      你只需要删除redCheck:

      }.foregroundColor(tipPercentage == 4 ? .red : .black)
      

      【讨论】:

        猜你喜欢
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        相关资源
        最近更新 更多