Home » Swift » Accessing variables from another ViewController in Swift

Accessing variables from another ViewController in Swift

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have the following ViewController:

class PageContentViewController: UIViewController {

    var pageIndex: Int

}

How would I access pageIndex from another ViewController?

I need to access pageIndex in this function:

func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

    //var index: Int
    //index = ?

    NSUInteger index = ((PageContentViewController*) viewController).pageIndex; // in Swift?

    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }

    index--;

    return [self viewControllerAtIndex:index]; // in Swift?
}
Answers:

Everything by default in swift is public, and thus if you declare something like this:

class SomeViewController: UIViewController {
    var someVariable: SomeType = someValue

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}

You can access it as long as you have an instance of it:

var myCustomViewController: SomeViewController = SomeViewController(nibName: nil, bundle: nil)
var getThatValue = myCustomViewController.someVariable

Questions:
Answers:

ViewController1.swift

class ViewController1: UIViewController {

    struct GlobalVariable{
        static var myString = String()
    }
}

ViewController2.swift

class ViewController2: UIViewController 
{

print(ViewController1.GlobalVariable.myString)

}

Questions:
Answers:

Here’s my attempt to convert that code to swift:

func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

    var pageController  = viewController as PageContentViewController
    var index: Int? = pageController.pageIndex

    if var idx: Int = index{
        if idx == 0{
            return nil
        }
        else{
            idx--
            return viewControllerAtIndex(idx)
        }
    }
    else{
        return nil
    }
}
class PageContentViewController: UIViewController {

    var pageIndex: Int?

}

Questions:
Answers:

I solved this way . .

class StaticLinker
{
     static var viewController : PageContentViewController? = nil
}

class PageContentViewController: UIViewController
{

    var pageIndex: Int
    StaticLinker.viewController = self
}

class AnotherClass
{
    StaticLinker.viewController.pageIndex = 100
}