Search code examples
iosswiftuipageviewcontroller

Passing variables from page view controller to another


Im trying to make a registration form using UIPageViewController, so I'm trying to pass variables from a child view to another.

This is my page view controller :

    class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {


var pageControl = UIPageControl()

// MARK: UIPageViewControllerDataSource

lazy var orderedViewControllers: [UIViewController] = {
    return [self.newVc(viewController: "First"),
            self.newVc(viewController: "Second"),
            self.newVc(viewController: "Third")]
}()

override func viewDidLoad() {
    super.viewDidLoad()
    self.dataSource = self
    self.delegate = self



    // This sets up the first view that will show up on our page control
    if let firstViewController = orderedViewControllers.first {
        setViewControllers([firstViewController],
                           direction: .forward,
                           animated: true,
                           completion: nil)
    }

    configurePageControl()

    // Do any additional setup after loading the view.
}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
    self.pageControl.numberOfPages = orderedViewControllers.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.black
    self.pageControl.pageIndicatorTintColor = UIColor.white
    self.pageControl.currentPageIndicatorTintColor = UIColor.black
    self.view.addSubview(pageControl)
}

func newVc(viewController: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: viewController)
}


// MARK: Delegate methords
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    let pageContentViewController = pageViewController.viewControllers![0]
    self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!
}

// MARK: Data source functions.
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: 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
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllers.count > previousIndex else {
        return nil
    }

    return orderedViewControllers[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: 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
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllersCount > nextIndex else {
        return nil
    }

    return orderedViewControllers[nextIndex]

And this is my registration controller

class RegisterViewController: UIViewController {
var username = ""
var email  = ""
var password = ""
var money = ""
var usn  = ""
@IBOutlet weak var textUsername: UITextField!
@IBOutlet weak var textEmail: UITextField!
@IBOutlet weak var textPassword: UITextField!
@IBOutlet weak var textMoney: UITextField!
@IBOutlet weak var labelUsername: UILabel!


@IBAction func btnValidate(_ sender: Any) {
    username = textUsername.text!
    usn = username
    email = textEmail.text!
    password = textPassword.text!
    print (username)
 //   labelUsername.text = username
  //  API.register(username: username, email: email, password: password)

}

@IBAction func btnSaveMoney(_ sender: Any) {
    money = String(textMoney.text!)
    print(money)
    print(username)

}
@IBAction func btnBegin(_ sender: Any) {
//   API.setMoney(money: money, username: username)
//   print(textMoney.text!)
    print("your name"+usn)
}
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
}
*/

My main goal is to pass pass the username from the First child to the Second so I can use it to use a web service theese are my storyboard and my registration form registration form

storyboard

I was trying to get username , password and email on the first page then pass the username to the next child view so i can send money amount to database


Solution

  • You need to use the following code

       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "yourSegueIdentiferHere" {
                  if let sendData = segue.destination as? destinationVC
                //All the data you want to send to viewController
                }
            }
    
        }
    

    This example is set up for multiple segue Identifiers. Simply continue the if statements if you have multiple identifiers


    Edit: If you do not want to use segues... Perhaps this will work for you ?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate=self
        self.dataSource=self
        let childViewController=storyboard?.instantiateViewController(withIdentifier: "some identifier of view") as! ChildViewController
        if let variable = dataToPass {
            print(variable)
        childViewController.variable = dataToPass
        }