【问题标题】:Access View's ViewModifier from UIHostingController从 UIHostingController 访问 View\'s ViewModifier
【发布时间】:2022-08-11 16:00:48
【问题描述】:

我有自定义 ViewModifier,它有一些我想从 UIHostingController 访问的属性。

MyViewModifier 被添加到 MyView 的根视图中,这是 UIHostingController 的 rootView:

struct MyViewModifier: ViewModifier {

    var property1: Bool = true
    var property2: String = \"\"

    func body(content: Content) -> some View {
        ... irelevant ...
    }
}

extension View {
    func myModifier(property1: Bool, property2: String) -> some View {
        return modifier(MyViewModifier(property1: property1, property2: property2))
    }
}
struct MyView: View {

    var body: some View {
        VStack { ... some content ... }
            .myModifier(property1: true, property2: \"Hello, world\")
    }
}

我有一个 UIHostingController 子类,它与这个问题无关,所以我已经重载了 init。 如果传递给此 HostingController 的 rootView 是否有可能具有 MyModifier 以及它的属性是什么?

    标签: swiftui


    【解决方案1】:

    不是直接的,只有当你以某种方式注入它们时,例如通过构造函数

    struct MyView: View {
        var property1 = true             // << default !!
        var property2 = "Hello, world"   // << default !!
    
        var body: some View {
          VStack { ... some content ... }
            .myModifier(property1: property1, property2: property2)  // not visible outside !!
        }
    }
    

    然后在其他地方你可以打电话

    UIHostingController(rootView: MyView(property1: false))
    // or both
    // UIHostingController(rootView: MyView(property1: false, property2: "Bye")) 
    
    

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2014-12-29
      • 2015-07-21
      • 2011-10-29
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多