I have three classes OnboardingViewController, OnboardingPageViewController, and OnboardingContentViewController.
In my ViewController class, I have a UIPageControl that updates whenever I press the UIButton "Next" beneath it. This is working as intended. However I want to make the UIPageControl updated according to when I swipe left/right on the UIPageViewController, but I'm not sure how to do this.
class OnboardingViewController: UIViewController {
#IBOutlet weak var nextButton: UIButton!
#IBOutlet weak var pageControl: UIPageControl!
var onboardingPageViewController: OnboardingPageViewController?
#IBAction func nextButtonTapped(_ sender: UIButton) {
if let index = onboardingPageViewController?.currentPageIndex {
switch index {
case 0:
onboardingPageViewController?.nextPage()
case 1:
onboardingPageViewController?.nextPage()
nextButton.setTitle("Get Started", for: .normal)
case 2:
//present login ViewController after final next button is tapped
default:
break
}
pageControl.currentPage = index + 1
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
if let pageViewController = destination as? OnboardingPageViewController {
onboardingPageViewController = pageViewController
}
}
}
class OnboardingContentViewController: UIViewController {
#IBOutlet var imageView: UIImageView!
#IBOutlet var titleLabel: UILabel!
#IBOutlet var introLabel: UILabel!
var index = 0
var contentTitle = ""
var intro = ""
var imageFile = ""
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = contentTitle
introLabel.text = intro
imageView.image = UIImage(named: imageFile)
}
}
class OnboardingPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pageTitle = ["Title1", "Title2", "Title3"]
var pageIntro = ["Description1","Description2","Description3"]
var pageImages = ["image1","image2","image3"]
var currentPageIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
if let startingViewController = contentViewController(at: currentPageIndex) {
setViewControllers([startingViewController], direction: .forward,animated: true, completion: nil)
}
}
func nextPage() {
currentPageIndex += 1
if let nextViewController = contentViewController(at: currentPageIndex){
setViewControllers([nextViewController], direction:.forward, animated: true, completion:nil)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = (viewController as! OnboardingContentViewController).index
index -= 1
return contentViewController(at:index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = (viewController as! OnboardingContentViewController).index
index += 1
return contentViewController(at:index)
}
func contentViewController(at index: Int) -> OnboardingContentViewController? {
if index < 0 || index >= pageIntro.count {
return nil
}
let storyboard = UIStoryboard(name: "Onboarding", bundle: nil)
if let pageContentViewController = storyboard.instantiateViewController(withIdentifier:"OnboardingContentViewController") as? OnboardingContentViewController {
pageContentViewController.imageFile = pageImages[index]
pageContentViewController.contentTitle = pageTitle[index]
pageContentViewController.intro = pageIntro[index]
pageContentViewController.index = index
return pageContentViewController
}
return nil
}
}
I tried adding the UIPageViewController delegate method to the first view controller but I'm finding that nothing is printing in the console. What am I missing?
class OnboardingViewController: UIViewController, UIPageViewControllerDelegate {
#IBOutlet weak var pageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
let pageController = self.storyboard!.instantiateViewController(withIdentifier: "OnboardingPageViewController") as! UIPageViewController
pageController.delegate = self
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed == true {
print("change page control number")
}
}
When you do let pageController = self.storyboard!.instantiateViewController..., you're initializing a new copy of the page view controller. This is unrelated to the one that your users see.
/// no!
let pageController = self.storyboard!.instantiateViewController(withIdentifier: "OnboardingPageViewController") as! UIPageViewController
pageController.delegate = self
Instead, you need to reference the existing page view controller that was added in the storyboard. It's automatically added as the first child of OnboardingViewController, so you can get it using self.children[0].
class OnboardingViewController: UIViewController, UIPageViewControllerDelegate {
#IBOutlet weak var pageControl: UIPageControl!
/// here!
var pageController: UIPageViewController {
return self.children[0] as! UIPageViewController
}
override func viewDidLoad() {
super.viewDidLoad()
pageController.delegate = self
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed == true {
print("change page control number")
}
}
}
Easiest way to create a post notification Here
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = (viewController as! OnboardingContentViewController).index
index -= 1
// post notification here with sending index value
return contentViewController(at:index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = (viewController as! OnboardingContentViewController).index
index += 1
// post notification here with sending index value
return contentViewController(at:index)
}
And listen in viewDidLoad of OnboardingViewController
Related
I have PageViewController and I'm loading ViewController's, every thing working fine. But when i update data in my ViewController of PageViewController it's getting crash in SecondViewController lbl1.text = "New Lbl1".
Error: Fatal error: Unexpectedly found nil while implicitly unwrapping
an Optional value
My Code in PageViewController :
import UIKit
class NewViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
#IBOutlet weak var pagerController: UIPageControl!
#IBOutlet weak var pageControllerView: UIView!
// The pages it contains
var pages = [UIViewController]()
// The UIPageViewController
var pageContainer: UIPageViewController!
// Track the current index
var currentIndex: Int?
private var pendingIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
// Setup the pages
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let page1 = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let page2: UIViewController! = storyboard.instantiateViewController(withIdentifier: "SecondViewController")
let page3: UIViewController! = storyboard.instantiateViewController(withIdentifier: "ThirdViewController")
pages.append(page1)
pages.append(page2)
pages.append(page3)
page1.variable = "This is strig..."
// Create the page container
pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageContainer.delegate = self
pageContainer.dataSource = self
pageContainer.setViewControllers([page1], direction: UIPageViewController.NavigationDirection.forward, animated: false, completion: nil)
// Add it to the view
pageControllerView.addSubview(pageContainer.view)
// set the frame of the pageContainer view to match its superview (the red view)
pageContainer.view.frame = pageControllerView.bounds
// let it resize if needed (such as device rotation)
pageContainer.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Configure our custom pageControl
view.bringSubviewToFront(pagerController)
pagerController.numberOfPages = pages.count
pagerController.currentPage = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UIPageViewController delegates
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.firstIndex(of:viewController)!
if currentIndex == 0 {
return nil
}
let previousIndex = abs((currentIndex - 1) % pages.count)
return pages[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.firstIndex(of:viewController)!
if currentIndex == pages.count-1 {
return nil
}
let nextIndex = abs((currentIndex + 1) % pages.count)
return pages[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
pendingIndex = pages.firstIndex(of:pendingViewControllers.first!)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
currentIndex = pendingIndex
if let index = currentIndex {
pagerController.currentPage = index
}
}
}
#IBAction func barBtnAction(_ sender: UIBarButtonItem) {
SecondViewController().setNewData()
}
}
My code in ViewController :
import UIKit
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblView: UITableView!
#IBOutlet weak var tblHeight: NSLayoutConstraint!
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tblView.delegate = self
tblView.dataSource = self
}
#IBAction func btn(_ sender: Any) {
print("ViewController second")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = "\(indexPath.row)"
return cell!
}
func setNewData() {
lbl1.text = "New Lbl1"
lbl2.text = "New Lbl2"
tblHeight.constant = 250
}
}
My PageVC
My SecondVC
This
SecondViewController().setNewData()
access the 2 nd vc without layout as you should load it from storyboard regradless of outlet connected / not hence a crash , you may need
let sec = pages[1] as! SecondViewController
sec.setNewData()
This SecondViewController() is used when the vc is completely created programmatically when you do it with 1 from storyboard all outlets will be nil as layout isn't loaded with that initializer in addition to that you create a new instance other than the 1 in pager controller
I have 3 types of VC's , 1st Vc, 2nd VC is PageViewController with 3 pages(I added PageController to normal ViewController here), third one is FinalViewController.
1st VC has button when i click it will move to 2nd VC that is PageViewController(It has 3 pages[3 ViewConrollers] working fine).
In PageViewController after loading first VC, it has view with gestures when i tap that i want to navigate FinalViewController completely.
Here navigation not working.
My 1st VC code
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = false
}
#IBAction func btn(_ sender: Any) {
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "NVC")
self.navigationController?.pushViewController(storyboard!, animated: true)
}
My PageViewController code
import UIKit
class NewViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
#IBOutlet weak var pagerController: UIPageControl!
#IBOutlet weak var pageControllerView: UIView!
// The pages it contains
var pages = [UIViewController]()
// The UIPageViewController
var pageContainer: UIPageViewController!
// Track the current index
var currentIndex: Int?
private var pendingIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
// Setup the pages
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let page1 = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let page2: UIViewController! = storyboard.instantiateViewController(withIdentifier: "SecondViewController")
let page3: UIViewController! = storyboard.instantiateViewController(withIdentifier: "ThirdViewController")
pages.append(page1)
pages.append(page2)
pages.append(page3)
page1.variable = "This is strig..."
// Create the page container
pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageContainer.delegate = self
pageContainer.dataSource = self
pageContainer.setViewControllers([page1], direction: UIPageViewController.NavigationDirection.forward, animated: false, completion: nil)
// Add it to the view
pageControllerView.addSubview(pageContainer.view)
// Configure our custom pageControl
view.bringSubviewToFront(pagerController)
pagerController.numberOfPages = pages.count
pagerController.currentPage = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UIPageViewController delegates
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.firstIndex(of:viewController)!
if currentIndex == 0 {
return nil
}
let previousIndex = abs((currentIndex - 1) % pages.count)
return pages[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.firstIndex(of:viewController)!
if currentIndex == pages.count-1 {
return nil
}
let nextIndex = abs((currentIndex + 1) % pages.count)
return pages[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
pendingIndex = pages.firstIndex(of:pendingViewControllers.first!)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
currentIndex = pendingIndex
if let index = currentIndex {
pagerController.currentPage = index
}
}
}
}
My `ViewConroller` code means which is loading in `PageViewController`
import UIKit
class ViewController: UIViewController {
var variable = String()
#IBOutlet weak var subView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Add gesture to incoming call view
let incomingCallsViewTap = UITapGestureRecognizer(target: self, action: #selector(incomingCallsViewTapFunction(_:)))
self.subView!.addGestureRecognizer(incomingCallsViewTap)
}
// Tap gestrure selector fuction
#objc func incomingCallsViewTapFunction(_ sender: UITapGestureRecognizer) {
let clvc = self.storyboard?.instantiateViewController(withIdentifier: "FVC") as! FinalViewController
self.navigationController?.pushViewController(clvc, animated: false)
}
#IBAction func btn(_ sender: Any) {
print("ViewController one")
print(variable)
}
}
navigationViewController is nil so I had to do the following:
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.pushViewController(clvc, animated: true)
// Tap gestrure selector fuction
#objc func incomingCallsViewTapFunction(_ sender: UITapGestureRecognizer) {
let clvc = self.storyboard?.instantiateViewController(withIdentifier: "FVC") as! FinalViewController
// self.navigationController?.pushViewController(clvc, animated: false)
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.pushViewController(clvc, animated: true)
}
I have a strange behavior with UIPageViewController.
Steps :
Open view controller
Tap on camera button
Choose picture
When return back, the included View Controller into the ContainerView take all place in View Controller
Here is my code :
class ContainerPagerViewController: BaseUIViewController {
// The UIPageViewController
var pageContainer: UIPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Create the page container
pageContainer = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
// Add it to the view
view.addSubview(pageContainer.view)
}
}
class RPViewController: BaseUIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var containerViewController: ContainerPagerViewController?
// Track the current index
var currentIndex: Int?
private var pendingIndex: Int?
private(set) lazy var pages: [UIViewController] = {
return [self.addViewController(identifier: "ViewController1"),
self.addViewController(identifier: "ViewController2"),
self.addViewController(identifier: "ViewController3"),
self.addViewController(identifier: "ViewController4"),
self.addViewController(identifier: "ViewController5"),
self.addViewController(identifier: "ViewController6")]
}()
override func viewDidLoad() {
super.viewDidLoad()
currentIndex = 0
containerViewController?.pageContainer.delegate = self
containerViewController?.pageContainer.dataSource = self
}
private func addViewController(identifier: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil) .
instantiateViewController(withIdentifier: identifier) as! UIViewController
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "containerSegue" {
containerViewController = segue.destination as? ContainerPagerViewController
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
pendingIndex = pages.index(of: pendingViewControllers.first! as! UIViewController)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
currentIndex = pendingIndex
}
}
}
}
I have an UIViewController with a UITableView. Then I create a PageViewController with two viewcontroller. Pageview doesn't work if I pass data to child. If I change
setViewControllers([subjective], direction: .Forward, animated: true, completion: nil)
to
setViewControllers([firstVC], direction: .Forward, animated: true, completion: nil)
Pageview work but data don't pass. I don't have any idea about it. Help me please. Thanks
Code Work:
pageview controller class:
import UIKit
class PageVC : UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var lblhoten = String()
var lblngaysinh = String()
var lblsodt = String()
lazy var VCArr: [UIViewController] = {
return [self.VCInstance("ThongTinBNPage2"),
self.VCInstance("ThongTinBNPage3")]
}()
private func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(name)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let firstVC = VCArr.first {
let subjective = self.storyboard?.instantiateViewControllerWithIdentifier("ThongTinBNPage2") as! VCSubjective
subjective.lblhoten = lblhoten
subjective.lblngaysinh = lblngaysinh
subjective.lblsodt = lblsodt
setViewControllers([subjective], direction: .Forward, animated: true, completion: nil)
}
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewcontrollerindex = VCArr.indexOf(viewController) else {
return nil
}
let previousindex = viewcontrollerindex - 1
guard previousindex >= 0 else {
return VCArr.last
}
guard VCArr.count > previousindex else {
return nil
}
return VCArr[previousindex]
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewcontrollerindex = VCArr.indexOf(viewController) else {
return nil
}
let nextindex = viewcontrollerindex + 1
guard nextindex < VCArr.count else {
return VCArr.first
}
guard VCArr.count > nextindex else {
return nil
}
return VCArr[nextindex]
}
public func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return VCArr.count
}
// The selected item reflected in the page indicator.
public func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
guard let firstviewcontroller = viewControllers?.first,
let firstviewcontrollerindex = VCArr.indexOf(firstviewcontroller) else {
return 0
}
return firstviewcontrollerindex
}
}
VCSubjective:
import UIKit
class VCSubjective: UIViewController {
#IBOutlet var hoten: UILabel!
#IBOutlet var ngaysinh: UILabel!
#IBOutlet var sodt: UILabel!
var lblhoten = String()
var lblngaysinh = String()
var lblsodt = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
hoten.text = lblhoten
ngaysinh.text = lblngaysinh
sodt.text = lblsodt
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The problem here is that you are referencing two completely different objects.
In viewDidLoad you create ThongTinBNPage2 viewController and then add it to the viewControllers property of the pageViewController. However, the objects stored in VCArr are two totally different viewControllers.
Let's think about it this way:
When viewDidLoad is called you create viewController object #1
Then you assign the viewController object #1 to the viewControllers object of the pageViewController making the value of viewControllers = [object #1]
In pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? and pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? you reference the VCArr object. On the first call to VCArr, it lazily creates two completely different view controller objects [object #2, object #3]
To fix this code you need to do the following:
if let firstVC = VCArr.first {
let subjective = firstVC // DO NOT create different VC here
subjective.lblhoten = lblhoten
subjective.lblngaysinh = lblngaysinh
subjective.lblsodt = lblsodt
setViewControllers([subjective], direction: .Forward, animated: true, completion: nil)
}
I'm new to protocols and pageview controllers and I tried to something I hoped was simple. To pass a variable value from the content viewcontroller to the page list viewcontroller but it doesn't work so I'm doing something wrong...
In my storyboard I have a ViewController (as the Page List viewcontroller) and embedded in a navigation controller. The navigation bar has a button on it.
There is a PageContentViewController that has a label.
The code I use follows (EDITED with the accepted solution provided by #Tom Elliott):
protocol setRoomOnScreenProtocol {
func updateRoomOnScreen(myRoom: String)
}
class ViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, setRoomOnScreenProtocol {
#IBAction func press1(sender: AnyObject) {
println("roomOnScreen: \(roomOnScreen)")
println("pageTitles: \(pageTitles)")
}
#IBOutlet weak var btn1: UIBarButtonItem!
let pageTitles = ["Room 1", "Room 2", "Room 3", "Room 4"]
var count = 0
var pageViewController : UIPageViewController!
var roomOnScreen: String = ""
override func viewDidLoad() {
super.viewDidLoad()
reset()
}
func updateRoomOnScreen(myRoom: String) {
roomOnScreen = myRoom
println("roomOnScreen (PGL): \(roomOnScreen)")
}
func reset() {
/* Getting the page View controller */
pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let pageContentViewController = self.viewControllerAtIndex(0)
self.pageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
index++
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
if (index <= 0) {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as! PageContentViewController
pageContentViewController.delegate = self
pageContentViewController.titleText = self.pageTitles[index]
pageContentViewController.pageIndex = index
return pageContentViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
and the PageContentViewController:
class PageContentViewController: UIViewController {
var pageIndex: Int?
var titleText : String!
var delegate: setRoomOnScreenProtocol!
#IBOutlet weak var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label1.text = self.titleText
}
override func viewDidAppear(animated: Bool) {
if let actualDelegate = self.delegate {
actualDelegate.updateRoomOnScreen(titleText)
} else {
println("error")
}
doMore()
}
func doMore() {
println("showing...:\(titleText)")
}
}
When I move through the pages I correctly get the output:
roomOnScreen (PGL): Room 1
showing...:Room 1
roomOnScreen (PGL): Room 2
showing...:Room 2
But when I hit the navigation bar button I get no value...
roomOnScreen:
pageTitles: [Room 1, Room 2, Room 3, Room 4]
What am I doing wrong...?
Thanks!
The line:
self.delegate = ViewController()
Is actually creating a brand new instance of ViewController each time it is called, so the original ViewController that is visible is not receiving the message.
I'd suggest setting the delegate when you initially create the pages:
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as! PageContentViewController
pageContentViewController.delegate = self