PageViewController-将变量传递给子视图

Jam*_*esG 5 ios uipageviewcontroller swift

是)我有的

我有一个ViewController(TutorialViewController)和一个UIPageViewController(TutorialPageViewController)。带有StoryBoard ID的情节提要中还有3个额外的视图:

  • GreenViewController
  • BlueViewController
  • RedViewController

我一直在关注本教程(对作者表示敬意,写得很好)。

在Green View Controller上,我定义了一个变量:

var passedVariable = ""
Run Code Online (Sandbox Code Playgroud)

然后在ViewDidLoad中将其打印出来。

这是两个具有代码的控制器:

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
}

}
Run Code Online (Sandbox Code Playgroud)

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)

}
Run Code Online (Sandbox Code Playgroud)

我尝试过的

我试过像这样先声明视图控制器:

let vc0 = GreenViewController(nibName: "GreenViewController", bundle: nil)
Run Code Online (Sandbox Code Playgroud)

然后像这样传递数据:

override func viewDidLoad() {
   vc0.passedVariable = "This was passed, Dance with Joy"
}
Run Code Online (Sandbox Code Playgroud)

控制台中没有任何输出。

我还尝试将上面的捆绑包更改为:

bundle: NSBundle.mainBundle()
Run Code Online (Sandbox Code Playgroud)

仍然纳达

我打算从alamofire请求中将数据加载到TutorialViewController上,我想将该数据传递给其中一个ViewController(绿色,蓝色,红色)

如何将已经从TutorialViewController中获取的数据传递给将要加载的子视图之一?

Jef*_*eff 3

首先,我要感谢您查看我的教程以及您所说的所有好话。

其次,我有一个解决方案给你!我继续将解决方案提交到我在教程中链接的GitHub 存储库。我也将在这里发布代码。

(1) 创建一个UIViewController子类来添加自定义属性。对于本示例,我选择添加 a,UILabel因为它在运行应用程序时最容易查看。

class ColoredViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

(2) 在内部,将每个“页面”Main.storyboard的自定义类更改为“身份检查器”。UIViewControllerColoredViewController

自定义类设置为 ColoredViewController

(3)UILabel在每个“页面”中添加一个并根据需要对其进行限制。我选择将其垂直和水平居中在容器中。不要忘记链接UILabelColoredViewController@IBOutlet weak var label: UILabel!

每页上的 UILabel

(4)可选:我删除了每个文本中的默认“标签”文本,这样如果我们从未在代码中设置标签的文本,我们将不会向用户显示“标签”。

删除标签默认文本

(5) 我们需要做一些 TLC,TutorialPageViewController以便它知道orderedViewControllers现在是一个ColoredViewController数组。为了让事情变得简单,我将粘贴整个课程:

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)

}
Run Code Online (Sandbox Code Playgroud)

(6) 里面TutorialViewController:让我们设置一下label.text。我选择使用viewDidLoad,但可以随意将此逻辑填充到网络请求完成块中。

override func viewDidLoad() {
    super.viewDidLoad()

    if let greenColoredViewController = tutorialPageViewController?.orderedViewControllers.first {
        greenColoredViewController.label.text = "Hello world!"
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!