如何从SwiftUI中该结构内部的类访问结构的变量?

时间:2020-05-07 02:30:11

标签: xcode swiftui

如何从结构内部的类中的函数访问@State变量。伪代码如下:

struct StructName: UIViewRepresentable {
    @State var variableName = value
    class className: NSObject {
        func functionName(parameters) {
            //How do I access variableName from here?
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用@Binding,并将其作为init的参数传递:

struct StructName: UIViewRepresentable {

    @Binding var variableName: Bool

    func makeUIView(context: Context) -> UIView {
        return UIView()
    }

    func updateUIView(_ uiView: UIView, context: Context) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(variableName: self.$variableName)
    }

     class Coordinator: NSObject {

        @Binding var variableName: Bool

        init(variableName: Binding<Bool>) {
           _variableName = variableName
        }

        func functionName() {
            //access variableName here
        }
    }
}

答案 1 :(得分:1)

这是可行的方法。具体类型用于演示目的。

struct StructName: UIViewRepresentable {
    @State var variableName: Bool = false

    class ClassName: NSObject {
        let boundVariable: Binding<Bool>

        init(variableName: Binding<Bool>) {
            self.boundVariable = variableName
        }

        func functionName(parameters: [String]) {
            boundVariable.wrappedValue = true
        }
    }

    // somewhere in place of ClassName instantiation below use
    // ClassName(boundVariable: $variableName)
}