Creating ViewControllers by swiping left programatically with new Data - ios

There is a single viewController with some data in it. After swiping left or right I want to create new viewControllers having the same UI but having different data. What is the best method to do this ? Should I be using UIPageViewController ?

Here is a solution for Swift 3 setting up a UIPageViewController programmatically.
The trick is to declare a lazy array called pages on your UIPageViewController.
In viewDidLoad using this array you can set up the viewControllers. Also, your dataSource is able to work with this array, handling the logic of changing the viewControllers. Right now, the dataSource is being implemented to continuously display the viewControllers, like a carousel. Modify it to your needs ;)
import Foundation
import UIKit
struct DisplayableData {
let title: String
let description: String
// etc...
}
class DataViewController: UIViewController {
var data: DisplayableData?
// You can add data as an initalizer parameter, depending on your design needs
init() {
// If you would create a xib for your DataViewController, than replace nib name with DataViewController to make it work
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class PageViewController: UIPageViewController {
lazy internal var pages: [DataViewController] = {
// If the UI is the same, reuse the viewController, no need to create multiple ones
// You could create a xib, and draw the UI there
let firstVC = DataViewController()
// Assign your data structure to your viewController
firstVC.data = DisplayableData(title: "first", description: "desc")
let secondVC = DataViewController()
secondVC.data = DisplayableData(title: "second", description: "desc")
let thirdVC = DataViewController()
thirdVC.data = DisplayableData(title: "third", description: "desc")
return [firstVC, secondVC, thirdVC]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
// Set your viewControllers
setViewControllers([pages.first!], direction: .forward, animated: false, completion: nil)
}
}
extension PageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
// Lets check if the viewController is the right type
guard let viewController = viewController as? DataViewController else {
fatalError("Invalid viewController type in PageViewController")
}
// Load the next one, if it is the last, load the first one
let presentedVCIndex: Int! = pages.index(of: viewController)
if presentedVCIndex + 1 > pages.count - 1 {
return pages.first
}
return pages[presentedVCIndex + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
// Lets check if the viewController is the right type
guard let viewController = viewController as? DataViewController else {
fatalError("Invalid viewController type in PageViewController")
}
// Load the previous one, if it is the first, load the last one
let presentedVCIndex: Int! = pages.index(of: viewController)
if presentedVCIndex - 1 < 0 {
return pages.last
}
return pages[presentedVCIndex - 1]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pages.count
}
}

Related

Type 'PageViewController' does not conform to protocol 'UIPageViewControllerDataSource'

I have been trying to use a UIPageViewController in my storyboard to create a set of sliding images, but I keep getting this error:
Type 'PageViewController' does not conform to protocol 'UIPageViewControllerDataSource'
And I don't understand why.
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
//for scroll view
lazy var subViewControllers:[UIViewController] = {
return[
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_1") as! ViewController_0,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_2") as! ViewController_1,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Slide_3") as! ViewController_2
]
}()
//after viewcontroller
func pageViewController(_pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex >= subViewControllers.count - 1) {
return nil
}
return subViewControllers[currentIndex + 1]
}
//before viewcontroller
func pageViewController(_pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if (currentIndex <= 0) {
return nil
}
return subViewControllers[currentIndex - 1]
}
override func viewDidLoad() {
super.viewDidLoad()
//setting the initial view for the slider
setViewControllers([subViewControllers[0]],direction: .forward, animated: true, completion: nil)
}
//making style a normal slide
required init?(coder: NSCoder) {
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return subViewControllers.count
}
}
There should be a space between the _ and the pageViewController parameter in your two methods that are part of the protocol (before/after pages).
The underscore denotes that the method, when called, does not need a label for that parameter.
For example:
func setBlob(_ blob: Blob) -> Bool {
}
Would look like this when it's called:
let myBlob = Blob()
setBlob(myBlob)
If it didn't have the _ there it would expect setBlob(blob: blob). It's convenient to be able to change or ignore the parameter names for the sake of code cleanliness. But since you don't have a space between the parameter label and the actual parameter name, it thinks the parameter name is _pageViewController.
There should be a red icon on the same line where the error shows and you can click that to automatically fill in the missing methods so you can easily see what is missing / incorrect. Your class has to implement all the required methods of the protocol and follow the same method signatures or else you'll get this error.

UIPageViewController setViewControllers

I am trying to implement a PageViewController that switches to a different ViewController when a button is pressed. I can successfully load each "child" ViewController using the setViewControllers method during viewDidLoad().
However when I call the setViewControllers method outside viewDidLoad(), it does not change the current "child" ViewController.
Can you call the method setViewControllers at any point or just once during viewDidLoad()? Also is there a way to change a variable in the pageviewcontrollers dataSource extensions?
My project consists of a entry ViewController with a "Settings" button and a ContainerView. Inside the ContainerView I have the UIPageViewController.
Code for PageViewController:
import UIKit
class PageViewController: UIPageViewController {
var slides = [SlideItem]()
var currentIndex: Int!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
initSlides()
}
override func viewDidLoad() {
super.viewDidLoad()
if let viewController = viewSlideViewController(currentIndex ?? 0){
let viewControllers = [viewController]
setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil)
}
dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewSlideViewController(_ index: Int) -> SlideViewController? {
guard let storyboard = storyboard,
let page = storyboard.instantiateViewController(withIdentifier: "SlideViewController") as? SlideViewController else {
return nil
}
page.slide = slides[index]
page.slideIndex = index
return page
}
func viewSettingsViewController(_ index: Int) -> SettingsViewController? {
guard let storyboard = storyboard,
let page = storyboard.instantiateViewController(withIdentifier: "SettingsViewController") as? SettingsViewController else {
return nil
}
return page
}
func initSlides(){
slides.append(SlideItem.init(filename: "Slide 1", comparison: false, highYield: false, videoURL: nil,
groupOrganSystem: ["A"],
groupMedicalSpecialty: ["B"]))
slides.append(SlideItem.init(filename: "Slide 2", comparison: false, highYield: false, videoURL: nil,
groupOrganSystem: ["A"],
groupMedicalSpecialty: ["B"]))
}
func sidebarCommands(button: String, state: Bool){
switch button {
case "settings":
self.setViewControllers([viewSettingsViewController(0)!], direction: .forward, animated: false, completion: nil)
print("settings")
default:
return
}
}
}
Extensions:
extension PageViewController : UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? SlideViewController,
let index = viewController.slideIndex,
index > 0 {
return viewSlideViewController(index - 1)
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? SlideViewController,
let index = viewController.slideIndex,
(index + 1) < slides.count {
return viewSlideViewController(index + 1)
}
return nil
}
}
You can use UIPageviewController in this way: (inheritance)
https://medium.com/how-to-swift/how-to-create-a-uipageviewcontroller-a948047fb6af
You can call setViewControllers at any point (I've been doing that).
The fact that it does not produce expected results is probably a result of bug in your code, include your code if you want to help out with that.
Thank you for your help, I figured out what I was doing wrong. I didn't have the right reference for the active PageViewController in the ContainerView.
So of course called the setViewControllers function on random PageViewController did not produce the correct results.
I found this answer explains how to correctly get a reference from a ContainerView

add observer and selector method not executing

When the user clicked in a cell it will go to the detail view controller here I post a notification with the selected index(object of a class). In detail view controller I used a container view. In this container view, I used a page view controller having two view controllers let's say A and B correspondingly. Both these two view controllers I created add observer method. But only 'A' view controller is registering for the notification. How can I get the selected index(object of a class) in B view controller..?
Code of detail View controller
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.post(name: Notification.Name(rawValue: mynotificationkey), object: nil, userInfo: ["object": self.treatobj])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pageView2" {
if let destination = segue.destination as? PageViewController {
destination.treatmentObject = treatobj
}
}
}
code of First View Controller that its executing fine
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(display(notification:)), name: Notification.Name(rawValue: mynotificationkey), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
func display(notification: Notification){
if let object = notification.userInfo {
if let obj = object["object"] {
treatObject = obj as! TreatMents
print(treatObject)
self.detailTitleLabel.text = treatObject.trtName
self.DesctextView.text = treatObject.desc1
}
}
}
code of second view controller that does not execute add observer
override func viewDidLoad() {
super.viewDidLoad()
about.text = treatObj.aboutkerala
//benifits = treatObj.benifits!
NotificationCenter.default.addObserver(self, selector: #selector(notfrecieved(notification:)), name: NSNotification.Name(rawValue: mynotificationkey), object: nil)
// Do any additional setup after loading the view.
}
func notfrecieved(notification: Notification) {
if let object = notification.userInfo {
if let obj = object["object"] {
print(obj)
treatObj = obj as! TreatMents
about.text = treatObj.aboutkerala
benifits = treatObj.benifits!
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
code of Page view controller
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var treatmentObject = TreatMents()
lazy var VCArray : [UIViewController] = {
return [self.VCInstance(name: "DescFisrtVC"),
self.VCInstance(name: "DescSecondVC"),
]
}()
private func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArray.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return VCArray.last
}
guard VCArray.count > previousIndex else {
return nil
}
return VCArray[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArray.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard nextIndex < VCArray.count else {
return VCArray.first
}
guard VCArray.count > nextIndex else {
return nil
}
return VCArray[nextIndex]
}
// A page indicator will be visible if both methods are implemented, transition style is 'UIPageViewControllerTransitionStyleScroll', and navigation orientation is 'UIPageViewControllerNavigationOrientationHorizontal'.
// Both methods are called in response to a 'setViewControllers:...' call, but the presentation index is updated automatically in the case of gesture-driven navigation.
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return VCArray.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first, let firstViewcontrollerIndex = VCArray.index(of: firstViewController) else {
return 0
}
return firstViewcontrollerIndex
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let firstVc = VCArray.first {
setViewControllers([firstVc], direction: .forward, animated: true, completion: nil)
}
// Do any additional setup after loading the view.
}
If you want to NotificationCenter then you need to load that class in memory first .
If you are added NotificationCenter in class but that class not loaded so this will be not working .
From the flow it looks to me that the two VCs in UIPageViewControllers didn't load yet when you are posting the notification.
Have a look at the explanation given in doc:
When defining a page view controller interface, you can provide the
content view controllers one at a time (or two at a time, depending
upon the spine position and double-sided state) or as-needed using a
data source. When providing content view controllers one at a time,
you use the setViewControllers(_:direction:animated:completion:)
method to set the current content view controllers. To support
gesture-based navigation, you must provide your view controllers using
a data source object.
So my guess is that since one page is loaded at a time, so your second controller didn't register for this event.
I have an objection on this process design using NSNotification, since from your code it looks to me that you want to evaluate your TreatMents objects on both screen when they gets load, IMHO you can either use Singleton concept (using session) or use KVO to fix this problem.
EDIT:
In PageViewController you implement these two functions:
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
that returns a VC from VCArray like:
return VCArray[previousIndex]
You also have treatmentObject in PageViewController, can you pass this variable to your two viewcontrollers while fetching it in above delegate functions like:
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArray.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return VCArray.last
}
guard VCArray.count > previousIndex else {
return nil
}
let VC = VCArray[previousIndex] // <------ Check this out
VC.treatObj = self.treatmentObject; // <------ Check this out
return VC
}
Or you can also save your selected treatment in session and retrieve it in two view controllers.

perform segue from pageViewController

My problem is as follows: I am using pageViewControllers to create a tutorial/onboarding page for an app i'm creating. A left swipe gesture on the last (3rd) page of my tutorial should perform a segue.
This is what I have as of now, but it is giving me a key value coding-compliancy error. I have double, triple checked my outlets, and swipeView is very much so connected properly.
class GrowController: UIViewController {
#IBOutlet weak var swipeView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(swipeView)
createGesture()
}
func createGesture() {
let showReg = UISwipeGestureRecognizer(target: self, action: #selector(showRegister))
showReg.direction = .left
self.swipeView.addGestureRecognizer(showReg)
}
func showRegister(gesture: UISwipeGestureRecognizer) {
performSegue(withIdentifier: "showRegister", sender: self)
}
}
That is the controller for the actual UIViewController (the specific page that is being displayed)
now ive also tried messing around with some logic in my TutorialViewController which is the UIPageViewController controlling the swipes form page to page etc.
Logic for that here
class TutorialViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var viewControllerIndex: Int?
//Array of my pages to load (GrowController is page3)
lazy var tutorialArray: [UIViewController] = {
return [self.tutorialInstance(name: "page1"), self.tutorialInstance(name: "page2"), self.tutorialInstance(name: "page3")]
}()
private func tutorialInstance(name: String?) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name!)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let firstViewController = tutorialArray.first {
setViewControllers([firstViewController], direction: .forward, animated: false, completion: nil)
}
}
// Scroll view
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for view in self.view.subviews {
if view is UIScrollView {
view.frame = UIScreen.main.bounds
}
else if view is UIPageControl {
view.backgroundColor = UIColor.clear
}
}
}
// Page View Controller delegate functions
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = tutorialArray.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard tutorialArray.count > previousIndex else {
// Added this line just testing around, nothing happened here though.
performSegue(withIdentifier: "ShowRegister", sender: self)
return nil
}
return tutorialArray[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = tutorialArray.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard nextIndex < tutorialArray.count else {
return nil
}
guard tutorialArray.count > nextIndex else {
return nil
}
return tutorialArray[nextIndex]
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return tutorialArray.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first, let firstViewControllerIndex = tutorialArray.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
}
Does is have something to do with the willTransitionTo pageView delegate method? I'm not familiar how to implement that, I have tried.
I thought that i could just add a subView to the Grow controller, put a swipe gesture in it, and perform a segue whenever the user swipes left from that page. As of right now, this code crashes the app upon loading of page3 (GrowController)
Any help GREATLY appreciated, I've been trying to figure this out for over a week and this is the second question on the topic i've posed. Thanks!
Don't use a UIPageViewController for this. That's very ironic, because I am usually the first to advise using UIPageViewController. But in this case it is doing too much of the work for you, and you cannot interfere in such a way as to customize it the way you're describing. You will need to use a simple paging UIScrollView; that way, you will be totally in charge of what happens, with fine-grained response thanks to the scroll view's delegate, and you'll have access to the underlying pan gesture recognizer and can modify its behavior.

PageViewController - Pass variables to child views

What I have
I have a ViewController (TutorialViewController) and a UIPageViewController (TutorialPageViewController). There are also 3 extra views on the storyboard with StoryBoard ID's:
GreenViewController
BlueViewController
RedViewController
I have been following this tutorial (Kudos to the author, very well written).
On the Green View Controller I have defined a variable:
var passedVariable = ""
And in the ViewDidLoad I print it out.
Here are the two controllers that have the code:
UIViewController (TutorialViewController):
class TutorialViewController: UIViewController {
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var containerView: UIView!
var tutorialPageViewController: TutorialPageViewController? {
didSet {
tutorialPageViewController?.tutorialDelegate = self
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tutorialPageViewController = segue.destinationViewController as? TutorialPageViewController {
self.tutorialPageViewController = tutorialPageViewController
}
}
#IBAction func didTapNextButton(sender: UIButton) {
tutorialPageViewController?.scrollToNextViewController()
}
}
extension TutorialViewController: TutorialPageViewControllerDelegate {
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageCount count: Int) {
pageControl.numberOfPages = count
}
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageIndex index: Int) {
pageControl.currentPage = index
}
}
UIPageViewController
class TutorialPageViewController: UIPageViewController {
weak var tutorialDelegate: TutorialPageViewControllerDelegate?
//let vc0 = GreenViewController(nibName: "GreenViewController", bundle: nil)
private(set) lazy var orderedViewControllers: [UIViewController] = {
// The view controllers will be shown in this order
return [self.newColoredViewController("Green"),
self.newColoredViewController("Red"),
self.newColoredViewController("Blue"), self.newColoredViewController("Pink")]
}()
override func viewDidLoad() {
super.viewDidLoad()
//self.vc0.passedVariable = "Passed Data"
dataSource = self
delegate = self
if let initialViewController = orderedViewControllers.first {
scrollToViewController(initialViewController)
}
tutorialDelegate?.tutorialPageViewController(self,
didUpdatePageCount: orderedViewControllers.count)
}
/**
Scrolls to the next view controller.
*/
func scrollToNextViewController() {
if let visibleViewController = viewControllers?.first,
let nextViewController = pageViewController(self,
viewControllerAfterViewController: visibleViewController) {
scrollToViewController(nextViewController)
}
}
private func newColoredViewController(color: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil) .
instantiateViewControllerWithIdentifier("\(color)ViewController")
}
/**
Scrolls to the given 'viewController' page.
- parameter viewController: the view controller to show.
*/
private func scrollToViewController(viewController: UIViewController) {
setViewControllers([viewController],
direction: .Forward,
animated: true,
completion: { (finished) -> Void in
// Setting the view controller programmatically does not fire
// any delegate methods, so we have to manually notify the
// 'tutorialDelegate' of the new index.
self.notifyTutorialDelegateOfNewIndex()
})
}
/**
Notifies '_tutorialDelegate' that the current page index was updated.
*/
private func notifyTutorialDelegateOfNewIndex() {
if let firstViewController = viewControllers?.first,
let index = orderedViewControllers.indexOf(firstViewController) {
tutorialDelegate?.tutorialPageViewController(self,
didUpdatePageIndex: index)
}
}
}
// MARK: UIPageViewControllerDataSource
extension TutorialPageViewController: UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0 else {
return orderedViewControllers.last
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else {
return orderedViewControllers.first
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
extension TutorialPageViewController: UIPageViewControllerDelegate {
func pageViewController(pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
notifyTutorialDelegateOfNewIndex()
}
}
protocol TutorialPageViewControllerDelegate: class {
/**
Called when the number of pages is updated.
- parameter tutorialPageViewController: the TutorialPageViewController instance
- parameter count: the total number of pages.
*/
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageCount count: Int)
/**
Called when the current index is updated.
- parameter tutorialPageViewController: the TutorialPageViewController instance
- parameter index: the index of the currently visible page.
*/
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageIndex index: Int)
}
What I have tried
I have tried declaring the View Controller first like so:
let vc0 = GreenViewController(nibName: "GreenViewController", bundle: nil)
And then passing the data like so:
override func viewDidLoad() {
vc0.passedVariable = "This was passed, Dance with Joy"
}
Nothing is printing out in the console.
I also tried changing the bundle above to:
bundle: NSBundle.mainBundle()
Still nada
Question
I plan to load data on the TutorialViewController from an alamofire request, I want to pass that data to one of the ViewControllers (green, blue, red)
How do I pass data that has been acquired from the TutorialViewController to one of the child views that will load?
First, I want to thank you for checking out my tutorial and all of the nice things you said about it.
Second, I have a solution for you! I went ahead and committed the solution to the GitHub repo I linked in the tutorial. I will also post the code here.
(1) Create a UIViewController subclass to add custom properties to. For this example, I chose to add a UILabel since it's the easiest to view when running the app.
class ColoredViewController: UIViewController {
#IBOutlet weak var label: UILabel!
}
(2) Inside Main.storyboard, change the custom class for each UIViewController "page" to ColoredViewController in the Identity Inspector.
(3) Add a UILabel to each "page" and constraint it however you'd like. I chose to vertically and horizontally center it in the container. Don't forget to link the UILabel to ColoredViewController's #IBOutlet weak var label: UILabel!.
(4) Optional: I deleted the default "Label" text in each one that way if we never set the label's text in code, we will not show "Label" to the user.
(5) We need to do some TLC to TutorialPageViewController so it knows that orderedViewControllers is now a ColoredViewController array. To make things easy, I'm just going to paste the entire class:
class TutorialPageViewController: UIPageViewController {
weak var tutorialDelegate: TutorialPageViewControllerDelegate?
private(set) lazy var orderedViewControllers: [ColoredViewController] = {
// The view controllers will be shown in this order
return [self.newColoredViewController("Green"),
self.newColoredViewController("Red"),
self.newColoredViewController("Blue")]
}()
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
if let initialViewController = orderedViewControllers.first {
scrollToViewController(initialViewController)
}
tutorialDelegate?.tutorialPageViewController(self,
didUpdatePageCount: orderedViewControllers.count)
}
/**
Scrolls to the next view controller.
*/
func scrollToNextViewController() {
if let visibleViewController = viewControllers?.first,
let nextViewController = pageViewController(self,
viewControllerAfterViewController: visibleViewController) {
scrollToViewController(nextViewController)
}
}
private func newColoredViewController(color: String) -> ColoredViewController {
return UIStoryboard(name: "Main", bundle: nil) .
instantiateViewControllerWithIdentifier("\(color)ViewController") as! ColoredViewController
}
/**
Scrolls to the given 'viewController' page.
- parameter viewController: the view controller to show.
*/
private func scrollToViewController(viewController: UIViewController) {
setViewControllers([viewController],
direction: .Forward,
animated: true,
completion: { (finished) -> Void in
// Setting the view controller programmatically does not fire
// any delegate methods, so we have to manually notify the
// 'tutorialDelegate' of the new index.
self.notifyTutorialDelegateOfNewIndex()
})
}
/**
Notifies '_tutorialDelegate' that the current page index was updated.
*/
private func notifyTutorialDelegateOfNewIndex() {
if let firstViewController = viewControllers?.first as? ColoredViewController,
let index = orderedViewControllers.indexOf(firstViewController) {
tutorialDelegate?.tutorialPageViewController(self,
didUpdatePageIndex: index)
}
}
}
// MARK: UIPageViewControllerDataSource
extension TutorialPageViewController: UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let coloredViewController = viewController as? ColoredViewController,
let viewControllerIndex = orderedViewControllers.indexOf(coloredViewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0 else {
return orderedViewControllers.last
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let coloredViewController = viewController as? ColoredViewController,
let viewControllerIndex = orderedViewControllers.indexOf(coloredViewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else {
return orderedViewControllers.first
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
extension TutorialPageViewController: UIPageViewControllerDelegate {
func pageViewController(pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
notifyTutorialDelegateOfNewIndex()
}
}
protocol TutorialPageViewControllerDelegate: class {
/**
Called when the number of pages is updated.
- parameter tutorialPageViewController: the TutorialPageViewController instance
- parameter count: the total number of pages.
*/
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageCount count: Int)
/**
Called when the current index is updated.
- parameter tutorialPageViewController: the TutorialPageViewController instance
- parameter index: the index of the currently visible page.
*/
func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
didUpdatePageIndex index: Int)
}
(6) Inside TutorialViewController: let's set the label.text. I chose to use viewDidLoad, but feel free to stuff this logic inside a network request completion block.
override func viewDidLoad() {
super.viewDidLoad()
if let greenColoredViewController = tutorialPageViewController?.orderedViewControllers.first {
greenColoredViewController.label.text = "Hello world!"
}
}
Hope this helps!
Obviously, according the comments, there's still confusion how this can be solved.
I'll try to introduce one approach and explain way this might make sense. Note though, that there are a few other viable approaches which can solve this problem.
The root view controller
First we take a look at the "root" controller which is an instance of TutorialViewController. This one is responsible to fetch/get/obtain/retrieve a "model". The model is and instance of pure data. It must be appropriate to define and initialise the page view controllers. Since we have a number of pages, it makes sense this model is some kind of array or list of some kind of objects.
For this example, I use an array of strings - just in order to illustrate how this can be implemented. A real example would obtain an array of likely more complex objects, where each of it will be rendered in its own page. Possibly, the array has been fetched from a remote resource with a network request.
In this example, the strings happen to be the "colour" of the page view controllers. We create an appropriate property for class TutorialViewController:
class TutorialViewController: UIViewController {
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var containerView: UIView!
private let model = ["Red", "Green", "Blue"]
...
Note that the property has private access: nobody else than the class itself should fiddle around with it.
Passing the Model from the Root Controller to its Embedded View Controller
The embedded view controller is an instance of TutorialPageViewController.
The root view controller passes the model to the embedded view controller in the method prepareForSegue. The embedded view controller must have an appropriate property which is suitable for its view of the model.
Note: A model may have several aspects or views. The model which has been initialised by the root view controller may not be appropriate to be passed as is to any of its presented view controllers. Thus, the root view controller may first filter, copy, reorder, or transform its model in order to make it suitable for the presented view controller.
Here, in this example, we take the model as is:
In class TutorialViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tutorialPageViewController = segue.destinationViewController as? TutorialPageViewController {
self.tutorialPageViewController = tutorialPageViewController
self.tutorialPageViewController!.model = self.model
}
}
Note that the TutorialViewController has itself a property (here model) which is set by the presenting view controller.
Here, the model is an array of strings. It should be obvious that the number of elements in the array should later become the number of pages in the page view controller. It should also be clear that each element is rendered on the corresponding page in a content view controller. Thus, we can say an element in the array serves as the "model" for each page.
We need to provide the property model in the TutorialPageViewController:
class TutorialPageViewController: UIPageViewController {
internal var model: [String]?
Note that the access is either public or internal, so that any presenting view controller can set it.
Passing the Model from the TutorialViewController to each Content View Controller
A page view controller (TutorialViewController) is responsible to create an array of content view controllers whose view render the page.
An easy approach to create the array of view controllers utilising a lazy property is shown below:
class TutorialPageViewController: UIPageViewController {
internal var model: [String]?
private(set) lazy var orderedViewControllers: [UIViewController] = {
// The view controllers will be shown in this order
assert(self.model != nil)
return self.model!.map {
self.newColoredViewController($0)
}
}()
The important part is here:
return self.model!.map {
self.newColoredViewController($0)
}
Here, we create N view controllers passing it the model (a String) in its factory function.
map returns an array of view controllers - suitable for the page view controller.
Once this has been implemented, the example works as in its original form.
You might now change the "factory" function which creates a view controller given a string as argument. For example you might set a label:
private func newColoredViewController(color: String) -> UIViewController {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContentViewController") as! MyContentViewController
vc.label = color
return vc
}
Here, again label is the "model" of the view controller. It's totally up the view controller how label will be rendered - if at all.
Based on some of the comments, I can see that there is one small snippet missing from #Jeff's answer that could help clarify how to actually transfer data from the TutorialPageViewController to the ColoredViewController. He likely assumed that this part of the answer was inferred. This can, however be frustrating if you don't know what to do from here.
With that being said, I'm going to piggy back off of his answer. Let's say, for example, that we want to change the text of the label inside the ColoredViewController from the TutorialPageViewController. We will set the text value to the background color of that particular view controller.
1) Start by defining the variable inside the ColoredViewController class and setting the label text to that value.
class ColoredViewController: UIViewController {
#IBOutlet weak var label: UILabel!
var labelText: String?
override func viewDidLoad() {
super.viewDidLoad()
if let text = labelText {
label.text = text
}
// Do any additional setup after loading the view.
}
}
2) Set the value of labelText in the newColoredViewController method that we already created inside the TutorialPageViewController class
private func newColoredViewController(color: String) -> ColoredViewController {
let newController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(color)ViewController") as! ColoredViewController
newController.labelText = label
return newController
}
The previously empty label inside the view controller will now display the color value.
Note: You don't necessarily have to have 3 separate view controllers for this example to apply to your particular application. You could have 1 view controller that is serving as a template for each page within the page view controller. In this case, you would not reference the new view controller in the newColoredViewController method with a variable value but instead with the static name of the one content view controller you want to use.

Resources