SwiftUI从页面发送动作到PageViewController。

问题描述 投票:1回答:1

我已经建立了一个 PageViewController 在SwiftUI中,按照已知的教程 与UIKit的接口,与 UIViewControllerRepresentable 等。

我的控制器数组由简单的SwiftUI视图组成。我通过一个简单的 IntroPage 结构来提供内容。视图是嵌套的,这是SwiftUI的良好做法,因此。

PageView
-   IntroScreen                // part of the pages array
    -   VStack 
        -   Text
        -   Image
        -   ButtonView         // a separate view struct
            - HStack
                - ForEach      // iterating through the buttons in my IntroPage Object
                    - Button
PageControl

现在我想加入一些 按钮 在这些视图上。它们应该可以通过我的 IntroPage 结构。其中一个方法是前进到PageViewController的下一页,另一个方法是告诉PageViewController先添加更多的页面,还有一个按钮是解散整个PageViewController。

我不明白,如何在PageViewController中访问这些方法,在哪里实现它们(实例视图?PageViewController的协调器?),以及如何到达我需要的对象(如 currentPage PageViewController的Binding变量)。)

例如,我已经实现了一个 forward() 函数,在PageViewController的协调器中。

func forward() {
   if parent.currentPage < parent.controllers.count - 1 {
       parent.currentPage += 1
   }
}

...如果我在最后一个视图的PageView旁边添加一个按钮,就能正常工作,有动画效果。但我仍然不能从子视图中的按钮调用这个函数。

有什么办法吗?

EDIT: 根据要求,这里是ButtonView中的情况。

struct IntroButtonView: View {
    var page: IntroPage
    var body: some View {
        HStack() {
           Button(action:dismiss) {
              Text("LocalizedButtonTitle")
           }
           // ... more buttons, based on certain conditions
        }
    }

    func dismiss() { 
         // how to dismiss the modally presented controller ?
    }

    func next()    { 
         // how to advance to the next page
    }

    func expand()  { 
         // how to add more pages to the pages array
    }
}

也可能是我完全错了,还是从 "事件 "而不是 "声明 "的角度来考虑......

ios swift swiftui uipageviewcontroller uiviewcontrollerrepresentable
1个回答
2
投票

OK,我想明白了。我不得不说,一开始并不直观。来自传统的基于事件的编程,这是一种完全不同的思维方式。

我用的是 @State 变量的视图主实例中。

我在视图的主实例中使用了 @Binding 变量来处理上游(ViewControllers,控件)和下游(子视图)的状态。所以,比如说,我用一个变量来告知 dataSourceUIPageViewController 是否要在当前控制器之前返回一个视图控制器。

对于驳回我使用的模式化呈现的控制器,我用了

@Environmen(\.presentationMode) var presentationMode

...

func dismiss() {
  self.presentationMode.wrapptedValue.dismiss()
}

在决定如何嵌套视图和选择什么变量进行绑定时,有一些注意事项,但现在我已经清楚了。最大的问题最终是 "真理之源 "应该固定在哪里。结果发现,就在 "中间",即控制器的下方,特定视图的上方。

希望对其他寻找类似东西的人有用。

© www.soinside.com 2019 - 2024. All rights reserved.