我正在使用UIPageViewController
,我的意图是在单击UIButton
中的一个UIViewController
时单击以切换当前视图。我已经在我的问题上进行了搜索,并找到了一些类似的主题,但是我无法做出正确的答案。
例如,我第二个UIViewController
vc2
中的按钮应将视图更改为vc3
。
RootPageViewController
import UIKit
class RootPageViewController: UIPageViewController, UIPageViewControllerDataSource {
lazy var viewControllerList:[UIViewController] = {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc1 = sb.instantiateViewController(withIdentifier: "timelineView")
let vc2 = sb.instantiateViewController(withIdentifier: "mainView")
let vc3 = sb.instantiateViewController(withIdentifier: "addView")
return [vc1, vc2, vc3]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
let secondViewController = viewControllerList[1]
self.setViewControllers([secondViewController], direction: .forward, animated: false, completion: nil)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let vcIndex = viewControllerList.firstIndex(of: viewController) else { return nil }
let previousIndex = vcIndex - 1
guard previousIndex >= 0 else { return nil }
guard viewControllerList.count > previousIndex else { return nil }
return viewControllerList[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let vcIndex = viewControllerList.firstIndex(of: viewController) else { return nil }
let nextIndex = vcIndex + 1
guard viewControllerList.count != nextIndex else { return nil }
guard viewControllerList.count > nextIndex else { return nil }
return viewControllerList[nextIndex]
}
}
第二个ViewController内部的按钮
@IBAction func addData(_ sender: Any) {
}
答案 0 :(得分:3)
在RootPageViewController
的{{1}}中,将第二个视图控制器按钮的目标添加到viewDidLoad
,并将self
方法添加到addData
。您可以使用RootPageViewController
并使用该方法移至最后一个视图控制器
setViewControllers
OR
在MainViewControlle中保留addData方法,并向其添加协议
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
if let secondViewController = viewControllerList[1] as? SecondViewController {
self.setViewControllers([secondViewController], direction: .forward, animated: false, completion: nil)
secondViewController.button.action = #selector(addData(_:))
}
}
@IBAction func addData(_ sender: Any) {
if let thirdViewController = viewControllerList.last {
self.setViewControllers([thirdViewController], direction: .forward, animated: false, completion: nil)
}
}
在RootPageViewController中确认此委托并添加委托方法
protocol MainVCDelegate {
func buttonPlusTapped()
}
class MainViewController: UIViewController {
@IBOutlet var buttonPlus: UIBarButtonItem!
var delegate: MainVCDelegate?
@IBAction func addData(_ sender: Any) {
delegate?.buttonPlusTapped()
}
}