从父类访问变量

时间:2015-07-29 14:02:01

标签: ios swift uinavigationcontroller parent-child uipageviewcontroller

我使用的是UIPageViewController

我的类 - ViewController(包含所有代码并且是数据源)运行PageItemController的实例。

我的UIPageControl(pControl)显示在ViewController的导航栏中。

我想要以下代码:

PageItemController

override func viewDidAppear(){

    let vController = the parent view controller // ViewController
    vController.pControl.currentPage = itemIndex

}

这是如何完成的?

2 个答案:

答案 0 :(得分:5)

使用视图控制器上的parentViewController属性:

if let parentVC = self.parentViewController as? MyParentViewController {
    itemIndex = parentVC.pControl // set variable here
}

答案 1 :(得分:2)

这有帮助吗?

    // Get the Navigation Controller
    let navControl = self.navigationController

    // Get all the pages in the hierarchy
    let allPages = navControl!.viewControllers

    // Get the current page
    let thisPageViewController = navControl!.visibleViewController

    // Work out which is the current page.
    // I'm sure someone else will have a more elgant way of doing this.
    let arrayOfPages : NSArray = NSArray(array: allPages)
    let thisPageIndex = arrayOfPages.indexOfObject(thisPageViewController)

    // Now get the parent and set a value in it.
    if thisPageIndex > 0 {
        let parentPageIndex = thisPageIndex - 1
        let parentView: AnyObject = arrayOfPages[parentPageIndex]
        parentView.pControl.currentPage = thisPageIndex
    } else {
        println("We are at the top and had to stop.")
    }