【问题标题】:SwiftUI Mathematical operations inside (some View)SwiftUI 里面的数学运算(部分视图)
【发布时间】:2020-04-07 17:45:27
【问题描述】:

我想问你一个关于在视图中使用数学运算的问题。

struct MyMenu: View {
    var cnt: Int = 0
    let colors: [Color] = [.red, .green, .blue]

    var body: some View {
        ForEach(colors, id: \.self) { color in
            Text(color.description)
                .padding()
                .background(color)

            cnt += 1
        }
    }
}

它给了我一个错误:

类型'()'不能符合'View';只有结构/枚举/类类型可以 符合协议

我不明白 SWIFTUI 语法有什么问题?为什么在some View中不能使用简单的数学运算。

有什么解决办法吗?谢谢!

【问题讨论】:

标签: swift swiftui


【解决方案1】:

您的主体中不能有“常规”代码,因为 SwiftUI 期望您有声明性代码来在其中生成 UI。

如果您想增加您的 cnt 属性,您需要在按钮操作中进行,例如:

Button(action: {
    cnt += 1
}) {
    Text("Click me to perform any action")
}

不要忘记您的 MyMenu 对象是一个结构,这意味着默认情况下它是不可变的。如果您的 cnt 属性未使用 @State 包装器或任何其他包装器包装,您将无法更新它,具体取决于您的需要:)

希望这会有所帮助! :)

【讨论】:

  • right 放这个的地方在哪里?在使用 Storyboards 时,有很多地方可以使用这种代码;我经常使用prepareForSegue 来排列我的鸭子,以便下一次呈现视图。但是,当我尝试修改 @State 变量时,SwiftUI 会给我警告 Modifying state during view update, this will cause undefined behavior.
【解决方案2】:

如果您确实需要在 SwiftUI 主体中执行此操作,可以使用 .onAppear() 修饰符来执行此操作,但正如 @UIChris 指出的那样,SwiftUI 期望使用声明性代码来仅生成 UI。

您的代码将如下所示:

struct MyMenu: View {
    var cnt: Int = 0
    let colors: [Color] = [.red, .green, .blue]

    var body: some View {
        ForEach(colors, id: \.self) { color in
            Text(color.description)
                .padding()
                .background(color)
                .onAppear(){
                    cnt += 1
                }
         }
     }
}

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2021-11-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多