I know the error means I have a NULL pointer, but I am unsure as to WHY that is, and I assume it must be something I did wrong in my code. My index starts at 1 because I want it to start in the middle view controller which is the home page. I am trying to make a page view controller to swipe between view controllers similar to snapchat. I have the following code:
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var viewControllersArray = [UIViewController]()
var pageIndex: Int?
let selectedIndex = 1
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
let vc1 = storyboard?.instantiateViewControllerWithIdentifier("ProfileView") as! ProfileViewController
let vc2 = storyboard?.instantiateViewControllerWithIdentifier("HomeView") as! HomeViewController
let vc3 = storyboard?.instantiateViewControllerWithIdentifier("MatchesView") as! MatchViewController
viewControllersArray.append(vc1)
viewControllersArray.append(vc2)
viewControllersArray.append(vc3)
self.dataSource = self
let pageContentViewController = self.viewControllerAtIndex(selectedIndex)
self.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) //Error here
}
the error occurs at this line:
self.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil) //Error here
The error is as follows: "Thread 1: EXC_BAD_ACCESS(code=2, address=0x7fff58d57ff8)
Here is my viewControllerAtIndex function:
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! PageViewController
pageContentViewController.pageIndex = index
return pageContentViewController
}
Here is my storyboard with the view controllers to swipe between:
Any and all help is greatly appreciated!
It looks like
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! PageViewController
pageContentViewController.pageIndex = index
return pageContentViewController
}
Needs to be:
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
return nil
}
return viewControllersArray[index]
}
Additionally
let selectedIndex = 1
should be
let selectedIndex = 0
since 1 will refer to the second page.
Related
I'm using PageViewController and tab bar. And I have a question which is 'how to move another view by touching button.' My app has 5 ViewControllers and they are on PageViewController. And the PageViewController is on ViewController. That ViewController is MainController. So I separated Main view, with about 4 : 1(PageViewController : tab bar). So tab bar is on MainController, MainController can changes ViewController when tab item is touched.
But what I want to make is a button on one of five ViewControllers which can change ViewController.
The button has not right to change ViewController. So I searched how to solve this problem but It couldn't find good solution.
I think the solution is very short, about 1 ~ 2 sentences.
I attached my code, so I hope anybody who know how to solve this problem please helps me.
I'm new in Swift, so explain detail please
This is a part of MainController
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController!
var subVC: [UIViewController] = []
var viewIndex: Int = 0
var tabIndicator1 = UIView()
var tabIndicator2 = UIView()
var tabIndicator3 = UIView()
var tabIndicator4 = UIView()
var tabIndicator5 = UIView()
var views = [UIView]()
override func viewDidLoad() {
super.viewDidLoad()
createVC() // make five ViewControllers
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! UIPageViewController
self.pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
self.pageViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
let startVC = subVC[0]
viewIndex = 0
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: true, completion: nil)
self.pageViewController.didMove(toParentViewController: self)
createTabBar() // make Tab Bar
createIndicator() // make Tab Indicator
self.pageViewController.dataSource = self
self.pageViewController.delegate = self
}
...
func createVC() { // I have five ViewController files
let HomeVC = VCInstance(name: "Home")
let AccessVC = VCInstance(name: "AccessLog")
let RegisterVC = VCInstance(name: "Register")
let SettingVC = VCInstance(name: "Setting")
let HelpVC = VCInstance(name: "Help")
subVC = [HomeVC, AccessVC, RegisterVC, SettingVC, HelpVC]
}
func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}
....
You can use this code it might be help you.
extension UIViewController {
func goNextPage(animated: Bool = true) {
guard let currentViewController = self.viewControllers?.first else { return }
guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
}
func goPreviousPage(animated: Bool = true) {
guard let currentViewController = self.viewControllers?.first else { return }
guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
}
}
I've a little problem with a UIContainerView. Each element from my containerView are under my ViewController generated by my UIPageController
This image will be more explicit :
So here, my blue button will be under the UIImageView (viewController at the bot) and i need it over it. I don't understand why, if someone have an I idea.
Result :
How i create my PageVieWController :
fileprivate func createPageViewController() {
let pageController = self.storyboard!.instantiateViewController(withIdentifier: "PageController") as! UIPageViewController
pageController.dataSource = self
if contentImages.count > 0 {
let firstController = getItemController(0)!
let startingViewControllers = [firstController]
pageController.setViewControllers(startingViewControllers, direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
}
pageViewController = pageController
addChildViewController(pageViewController!)
self.view.addSubview(pageViewController!.view)
pageViewController!.didMove(toParentViewController: self)
}
And how i instantiate my pageItem :
fileprivate func getItemController(_ itemIndex: Int) -> ABTutorialPageItemViewController? {
if itemIndex < contentImages.count {
let pageItemController = self.storyboard!.instantiateViewController(withIdentifier: "ItemController") as! ABTutorialPageItemViewController
pageItemController.itemIndex = itemIndex
pageItemController.imageName = contentImages[itemIndex]
return pageItemController
}
return nil
}
If you want to manipulate, show directly in action you can use this project :
https://github.com/YanisSOTO/Simple-UIPageViewController-Example
Solved by replacing :
self.view.addSubview(pageViewController!.view)
to :
self.containerView.addSubview(pageViewController!.view)
Using the following code, I have a series of view controllers embedded in a page view controller that I'm swiping through. I just can't find a way to segue to another view controller via a bar button press. I'm planning on writing a separate function for each bar button icon in each view controller.
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
private var pages: [UIViewController]!
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.pages = [
self.storyboard!.instantiateViewControllerWithIdentifier("FirstNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("SecondNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("ThirdNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("FourthNav") as! UINavigationController
]
let startingViewController = self.pages.first! as UIViewController
self.setViewControllers([startingViewController], direction: .Forward, animated: false, completion: nil)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
// if currently displaying last view controller, return nil to indicate that there is no next view controller
return (index == self.pages.count - 1 ? nil : self.pages[index + 1])
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
// if currently displaying first view controller, return nil to indicate that there is no previous view controller
return (index == 0 ? nil : self.pages[index - 1])
}
}
Change your implementation of PageViewController to the following (I made some changes in the methods you already implemented, and I added a new instance method.)
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
private var pages: [UINavigationController]!
private var currentPageIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.pages = [
self.storyboard!.instantiateViewControllerWithIdentifier("FirstNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("SecondNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("ThirdNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("FourthNav") as! UINavigationController
]
(self.pages[0].topViewController as! FirstViewController).parentPageViewController = self
(self.pages[1].topViewController as! SecondViewController).parentPageViewController = self
(self.pages[2].topViewController as! ThirdViewController).parentPageViewController = self
(self.pages[3].topViewController as! FourthViewController).parentPageViewController = self
self.currentPageIndex = 0
let startingViewController = self.pages.first! as UINavigationController
self.setViewControllers([startingViewController], direction: .Forward, animated: false, completion: nil)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
self.currentPageIndex = index
// if currently displaying last view controller, return nil to indicate that there is no next view controller
return (self.currentPageIndex == self.pages.count - 1 ? nil : self.pages[self.currentPageIndex + 1])
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
self.currentPageIndex = index
// if currently displaying first view controller, return nil to indicate that there is no previous view controller
return (index == 0 ? nil : self.pages[index - 1])
}
func displayPageForIndex(index: Int, animated: Bool = true) {
assert(index >= 0 && index < self.pages.count, "Error: Attempting to display a page for an out of bounds index")
// nop if index == self.currentPageIndex
if self.currentPageIndex == index { return }
if index < self.currentPageIndex {
self.setViewControllers([self.pages[index]], direction: .Reverse, animated: true, completion: nil)
} else if index > self.currentPageIndex {
self.setViewControllers([self.pages[index]], direction: .Forward, animated: true, completion: nil)
}
self.currentPageIndex = index
}
}
Now, in each of your child view controllers, add two pieces of code:
A property that maintains a weak reference to the parent PageViewController instance.
weak var parentPageViewController: PageViewController!
An IBAction to which you connect each of your bar button items. You may need to change the body of this method depending on how your Storyboard is set up.
#IBAction func barButtonTapped(sender: UIBarButtonItem) {
var newIndex = -1
switch sender.title! {
case "First":
newIndex = 0
case "Second":
newIndex = 1
case "Third":
newIndex = 2
case "Fourth":
newIndex = 3
default: break
}
self.parentPageViewController.displayPageForIndex(newIndex)
}
Does each controller need to be embedded in a UINavigationController? You could just have a UINavigationController embed a single UIViewController, that view controller references a pageviewcontroller and a barButtonItem, when the barButtonItem is tapped trigger an action that tells the pageviewcontroller to change indexes.
Or if you want to go with your current plan of action which is a barButtonItem in each UINavigationController, write a protocol with a delegate method didSelectBarButtonAtIndex or something, then give each UINavigationController a delegate property, have the pageviewcontroller conform to the protocol and become the delegate for each nav controller. Then when a bar button is tapped, call the delegate method, which should make the page controller change it's index.
Courtesy of Using UIPageViewController with swift and multiple view controllers, I'm embedding navigation controllers in a UIPageViewController so I can horizontally scroll thru them (like swipe nav). Problem:
When I reach the first or last nav controller, and then swipe in the opposite direction, the 2nd-to-first/last nav controller will duplicate. So I'll have 5 nav controllers. For example:
Starting at FirstNav, swipe left all the way to FourthNav. When I swipe right through the array of controllers from FourthNav, the sequence will be: ThirdNav, ThirdNav, SecondNav, FirstNav. Can anyone find out what's going on?
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var index = 0
var identifiers: NSArray = ["FirstNav", "SecondNav", "ThirdNav", "FourthNav"]
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
let startingViewController = self.viewControllerAtIndex(self.index)
let viewControllers: NSArray = [startingViewController]
self.setViewControllers(viewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
}
func viewControllerAtIndex(index: Int) -> UINavigationController! {
if index == 0 {
return self.storyboard!.instantiateViewControllerWithIdentifier("FirstNav") as! UINavigationController
}
if index == 1 {
return self.storyboard!.instantiateViewControllerWithIdentifier("SecondNav") as! UINavigationController
}
if index == 2 {
return self.storyboard!.instantiateViewControllerWithIdentifier("ThirdNav") as! UINavigationController
}
if index == 3 {
return self.storyboard!.instantiateViewControllerWithIdentifier("FourthNav") as! UINavigationController
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let identifier = viewController.restorationIdentifier
let index = self.identifiers.indexOfObject(identifier!)
//if the index is the end of the array, return nil since we dont want a view controller after the last one
if index == identifiers.count - 1 {
return nil
}
//increment the index to get the viewController after the current index
self.index = self.index + 1
return self.viewControllerAtIndex(self.index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let identifier = viewController.restorationIdentifier
let index = self.identifiers.indexOfObject(identifier!)
//if the index is 0, return nil since we dont want a view controller before the first one
if index == 0 {
return nil
}
//decrement the index to get the viewController before the current one
self.index = self.index - 1
return self.viewControllerAtIndex(self.index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
The issue has to do with your calculation of the index variable in your pageViewController(_:viewControllerBeforeViewController:) and pageViewController(_:viewControllerAfterViewController:) methods. To simplify that logic and the overall logic of your page view controller, you should change your implementation to the following:
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
private var pages: [UIViewController]!
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.pages = [
self.storyboard!.instantiateViewControllerWithIdentifier("FirstNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("SecondNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("ThirdNav") as! UINavigationController,
self.storyboard!.instantiateViewControllerWithIdentifier("FourthNav") as! UINavigationController
]
let startingViewController = self.pages.first! as UIViewController
self.setViewControllers([startingViewController], direction: .Forward, animated: false, completion: nil)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
// if currently displaying last view controller, return nil to indicate that there is no next view controller
return (index == self.pages.count - 1 ? nil : self.pages[index + 1])
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let index = (self.pages as NSArray).indexOfObject(viewController)
// if currently displaying first view controller, return nil to indicate that there is no previous view controller
return (index == 0 ? nil : self.pages[index - 1])
}
}
You don't even need to maintain an index instance variable, and this implementation does not do so. But you could, if you wanted. This solution also instantiates a single instance of each UINavigationController instead of instantiating a new one every time the user attempts to scroll to a different page, which conserves memory and preserves the state of the view controllers as the user scrolls between them.
Please excuse the non-descriptive pages variable name. I didn't want to create a conflict with UIPageViewController's viewControllers property.
I finnaly synchronized my segmentedController to the UIPageViewController in this way: when I swipe between pages, the segmented controller changes it's segment index. I want to know how to do the reverse too, when segmentedController's segment is tapped, to change the pageViewController page by segmentedController index. Here is my code:
class photoPageViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var segmentedControl: UISegmentedControl!
private var pageViewController: UIPageViewController?
var controllers = [thePageViewController]()
var thePage = thePageViewController()
override func viewDidLoad() {
super.viewDidLoad()
createPageViewController()
setupPageControl()
}
private func createPageViewController() {
var pageController = self.storyboard!.instantiateViewControllerWithIdentifier("PageController") as! UIPageViewController
pageController.dataSource = self
pageController.delegate = self
var firstController = getItemController(thePage.itemIndex)!
var startingViewControllers: NSArray = [firstController]
pageController.setViewControllers(startingViewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
pageViewController = pageController
addChildViewController(pageViewController!)
self.view.addSubview(pageViewController!.view)
pageViewController!.didMoveToParentViewController(self)
}
private func setupPageControl() {
let appearance = UIPageControl.appearance()
appearance.pageIndicatorTintColor = UIColor.grayColor()
appearance.currentPageIndicatorTintColor = UIColor.whiteColor()
appearance.backgroundColor = UIColor.darkGrayColor()
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let itemController = viewController as! thePageViewController
if itemController.itemIndex > 0 {
return getItemController(itemController.itemIndex-1)
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let itemController = viewController as! thePageViewController
if itemController.itemIndex+1 < 3 {
return getItemController(itemController.itemIndex+1)
}
return nil
}
func getItemController(itemIndex: Int) -> UIViewController? {
var vc: thePageViewController? = nil
switch itemIndex {
case 0:
vc = self.storyboard!.instantiateViewControllerWithIdentifier("ViewController0") as! firstPhotoViewController
vc?.itemIndex = itemIndex
case 1:
vc = self.storyboard!.instantiateViewControllerWithIdentifier("ViewController1") as! secondPhotoViewController
vc?.itemIndex = itemIndex
case 2:
vc = self.storyboard!.instantiateViewControllerWithIdentifier("ViewController2") as! thirdPhotoViewController
vc?.itemIndex = itemIndex
default:
return nil
}
return vc
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return 3
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
func pageViewController(photoPageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers pageViewController: [AnyObject],
transitionCompleted completed: Bool)
{
if (!completed)
{
return;
}
segmentedControl.selectedSegmentIndex = thePageIndex
//thePageIndex is a global variable that changes when views from pageViewController appear
}
#IBAction func segmentedFunction(sender: AnyObject) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
getItemController(0)
case 1:
getItemController(1)
case 2:
getItemController(2)
default:
println("...")
}
}}
I think you need to change your code a little bit! In my case I create several vc and put them to one array.
func createArrayOfControllers(){
newsLenta = self.storyboard?.instantiateViewControllerWithIdentifier("NewsLentaTableViewController") as NewsLentaTableViewController
mainPage = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageTableViewController") as MainPageTableViewController
onlinetranslation = self.storyboard?.instantiateViewControllerWithIdentifier("SingleTopicTableViewController") as SingleTopicTableViewController
tableViewControllers = [newsLenta, mainPage, onlinetranslation]
}
where tableViewController is global var var tableViewControllers = [UITableViewController]() ! I signed type TableViewController because all my vs's are type of table View controller. So the next function you need to change is
func viewControllerAtIndex(index : Int) -> UIViewController? {
if index > 2 || index < 0 {
return nil
}
return tableViewControllers[index]
}
In the end you just need to create action of segmentControl and reset your vc by index. Using this function:
func resetToMainPage(index: Int!) {
/* Getting the page View controller */
mainPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as UIPageViewController
self.mainPageViewController.dataSource = self
self.mainPageViewController.delegate = self
let pageContentViewController = self.viewControllerAtIndex(index)
segmentedControl.selectedSegmentIndex = index
self.mainPageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.mainPageViewController.view.frame = CGRectMake(0, 95, self.view.frame.width, self.view.frame.height)
self.addChildViewController(mainPageViewController)
self.view.addSubview(mainPageViewController.view)
self.mainPageViewController.didMoveToParentViewController(self)
}
My question for your how do you update thePageIndex... I dont get that...
I found the way how to change UIPageViewController's content viewcontroller. I dont know is it right way or wrong but it works. Here is a code:
put this to viewdidload:
segmentControl.addTarget(self, action: "selectPageIndexBySegmentControl", forControlEvents: UIControlEvents.ValueChanged)
put it separte from viewdieload:
func selectPageIndexBySegmentControl(){
switch segmentControl.selectedIndex {
case 0:
println("zero index were selected")
pageContentViewController = self.viewControllerAtIndex(0)
mainPageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
case 1:
println("first element were selected")
pageContentViewController = self.viewControllerAtIndex(1)
mainPageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
case 2:
println("second element were selected")
pageContentViewController = self.viewControllerAtIndex(2)
mainPageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
default:
break
}
}