小编典典

在Swift中从另一个ViewController访问变量

swift

我有以下内容ViewController

class PageContentViewController: UIViewController {

    var pageIndex: Int

}

我如何pageIndex从另一个ViewController 访问?

我需要访问pageIndex此功能:

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?
}

阅读 531

收藏
2020-07-07

共1个答案

小编典典

默认情况下,swift中的所有内容都是公开的,因此,如果您声明以下内容:

class SomeViewController: UIViewController {
    var someVariable: SomeType = someValue

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

只要拥有它的实例,就可以访问它:

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