【问题标题】:Swift: How to modify struct property outside of the struct's scopeSwift:如何在结构范围之外修改结构属性
【发布时间】:2022-01-15 15:02:08
【问题描述】:

在 Swift/SwiftUI 中编程,并在尝试启用视图以修改不同结构的属性时遇到此问题。

有没有办法修改属于结构的属性,而无需为结构创建对象?如果有,是什么?

【问题讨论】:

    标签: swift xcode struct swiftui


    【解决方案1】:

    现在,您正在尝试访问 showOverlap,就好像它是 MainView 上的 static 变量一样——这不起作用,因为它不是静态属性,即使是,您也会需要引用您所展示的 MainView 的特定实例——在 SwiftUI 中我们通常会避免这种情况,因为 Views 是可传递的。

    相反,您可以传递Binding——这是在 SwiftUI 中将父视图状态传递给子视图的方法之一。

    
    struct MainView: View {
        @State var showOverlap = false
        
        var body: some View {
            ZStack {
                Button(action: {
                    showOverlap = true
                }) {
                    Text("Button")
                }
                if showOverlap {
                    Overlap(showOverlap: $showOverlap) //<-- Here
                }
            }
        }
    }
    
    
    struct Overlap: View {
        @Binding var showOverlap : Bool  //<-- Here
        
        var body: some View {
            ZStack {
                RoundedRectangle(cornerRadius: 40)
                    .aspectRatio(130/200, contentMode: .fit)
                    .foregroundColor(.gray)
                
                    Button(action: {
                       showOverlap = false //<-- Here
                    }, label: {
                        Text("Back")
                    })
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2015-02-02
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多