ios - swift:向前和向后翻转 Action

标签 ios swift

我有UIPageViewController。我想通过单击按钮来翻转页面。我想像 viewControllerAfterviewControllerBefore 一样向前和向后翻转页面。我使用此代码来翻页,但它不起作用:

@IBAction func nextAction(_ sender: Any) {

    let pageController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! UIPageViewController

    pageController.dataSource = self
    pageController.delegate = self

    let firstController = getContentViewController(withIndex: 0)!
    let secondController = getContentViewController(withIndex: 1)!
    let contentControllers = [firstController, secondController]

    pageController.setViewControllers(contentControllers, direction: .forward, animated: true, completion: nil)
}

如何解决?

更新

extension UIPageViewController {

    func goToNextPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
        setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
    }

    func goToPreviousPage(animated: Bool = true) {
        guard let currentViewController = self.viewControllers?.first else { return }
        guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
        setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
    }

}

最佳答案

首先,您必须有一个事件的 pageVC 才能导航到特定的 VC ,而不是

pageController.setViewControllers(contentControllers, direction: .forward, animated: true, completion: nil)

您必须仅设置要导航到的 vc

pageController.setViewControllers([firstController], direction: .forward, animated: true, completion: nil)

并跟踪它的索引,因此当用户再次滚动时,将调用 dataSource 方法来加载正确的 VC ,我创建了一个演示 Here做同样的工作

关于ios - swift:向前和向后翻转 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51498882/

相关文章:

xcode - Swift - 读取文件

swift - 如何为泛型类型添加扩展?

xcode - 使用 Swift 的预期声明错误

json - Swift,当 key 未知/动态时,如何使用 Decodable 和 Codable 解析/解码 JSON

ios - SKNode 内的 CoreGraphics 元素

ios - 如何在IOS中的UITabBarController上强制RTL?

ios - 将表格 View 单元格中的颜色 slider 设置为单元格的全长

ios - GPUImage iOS 中未显示文本叠加层

objective-c - Game Center 不响应 authenticateWithCompletionHandler 请求 (iOS)

swift - 如何在 Swift 中过滤字典数组