UIPageViewController page location dots appear overlapped? - ios

I am having this issue where the dots in my PageViewController are appearing with a dot in-between two dots. When I save the pages and load them, then the pages appear with normal dots, the appropriate number of dots, and normal placement. Here is an image of what I am talking about.
Hierarchy debugger shows this image. Obviously the dots are appearing multiple times, behind one another.
Here is the code that I use for the dots:
func configurePageControl() {
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
self.pageControl.numberOfPages = storyPageViewControllers.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.black
self.pageControl.alpha = 0.5
self.pageControl.pageIndicatorTintColor = UIColor.white
self.pageControl.currentPageIndicatorTintColor = UIColor.black
self.view.addSubview(pageControl)
}
configurePageControl() is called in the viewDidAppear. I tried moving it to the viewDidLoad, but it only showed one dot and didn't show more as I made new pages.
Here is my extension on the UIPageViewController class if you want to see how my pages are created:
extension BookPageViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = storyPageViewControllers.index(of: viewController as! TemplateViewController) else { return nil }
if viewControllerIndex == 0 { return nil } // Page won't scroll below first page.
let previousIndex = viewControllerIndex - 1
guard storyPageViewControllers.count > previousIndex else { return nil }
currentPage = Double(previousIndex)
return storyPageViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = storyPageViewControllers.index(of: viewController as! TemplateViewController) else { return nil }
let nextIndex = viewControllerIndex + 1
let storyPageViewControllersCount = storyPageViewControllers.count
guard storyPageViewControllersCount != nextIndex else { return nil }
guard storyPageViewControllersCount > nextIndex else { return nil }
currentPage = Double(nextIndex)
return storyPageViewControllers[nextIndex]
}
// MARK: Delegate function
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
self.pageControl.currentPage = storyPageViewControllers.index(of: pageContentViewController as! TemplateViewController)!
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return storyPageViewControllers.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = storyPageViewControllers.index(of: firstViewController as! TemplateViewController) else
{ return 0 }
return firstViewControllerIndex
}
}

1- Definitely don't call configurePageControl() on viewDidappear. Is wrong, can give u bugs and weird user experience.
2- U r calling configurePageControl() 3 times. By chance do you have 3 viewController on your pageViewController?
Solutions:
A: I would create the pageViewController in Storyboard and just update the dots number just after u finish setting all ViewControllers.
B: Keep all as is BUT:
1- Move configurePageControl() to ViewDidLoad()
2- Leave it like this, with initial dots to 0
(tip 1: avoid using "self" when is not necessary)
(tip 2: avoid using frames, use constraints)
func configurePageControl() {
pageControl = UIPageControl(frame: CGRect(x: 0,y:
UIScreen.main.bounds.maxY - 50,width:
UIScreen.main.bounds.width,height: 50))
pageControl.numberOfPages = 0
pageControl.currentPage = 0
pageControl.tintColor = UIColor.black
pageControl.alpha = 0.5
pageControl.pageIndicatorTintColor = UIColor.white
pageControl.currentPageIndicatorTintColor = UIColor.black
view.addSubview(pageControl)
}
3- Just after u finish setting all viewControllers, update the pageViewControllers dots number
pageControl.numberOfPages = storyPageViewControllers.count
Notice it should work if placed here, but is not the right place. U can do it just for testing.
func presentationCountForPageViewController(pageViewController:
UIPageViewController) -> Int {
pageControl.numberOfPages = storyPageViewControllers.count
return storyPageViewControllers.count
}

UIPageViewController already has a page control; all you have to do is show it (by implementing the two data source methods that do that). You shouldn't be adding another page control to it. The included page control already syncs itself to the page view controller. You're doing far more work than you should be doing.

Related

How to Capture click event on Page Control swift

I follow a tutorial on how to create UIPageControl and when I click on the page indicator it do not change the page
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: 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
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: 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
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 40,width: UIScreen.main.bounds.width,height: 40))
self.pageControl.numberOfPages = orderedViewControllers.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.gray
self.pageControl.pageIndicatorTintColor = UIColor.gray
self.pageControl.currentPageIndicatorTintColor = UIColor.white
self.view.addSubview(pageControl)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!
}
In configurePageControl() add pageControl.addTarget
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 40,width: UIScreen.main.bounds.width,height: 40))
//add target for dots
pageControl.addTarget(self, action: #selector(self.pageControlSelectionAction(_:)), for: .touchUpInside)
self.pageControl.numberOfPages = orderedViewControllers.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.gray
self.pageControl.pageIndicatorTintColor = UIColor.gray
self.pageControl.currentPageIndicatorTintColor = UIColor.white
self.view.addSubview(pageControl)
}
Then add the method to change page when a dot is selected.
#objc func pageControlSelectionAction(_ sender: UIPageControl) {
//move page to wanted page
let page: Int? = sender.currentPage
self.pageViewController?.setViewControllers([[orderedViewControllers[page!]]], direction: .forword, animated: true, completion: nil)
}
In my case(Xcode 13), I received previous currentPage.
So use dispatchQueue asyncAfter
#objc func pageControlSelectionAction(_ sender: UIPageControl) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
let page: Int? = sender.currentPage
//scroll
}
}
Also I just tested 'DispatchQueue.main.async' was fine.

Fast scroll UIPageViewController prevents viewcontroller from updating

I have a UIPageviewcontroller which got two controllers inside. As you swipe to the next, I use the viewController argument to set the appropriate delegate. But I experience that if you swipe too fast, the function viewControllerAfter isn't updating the viewController correctly. The initially swipe should update the index of the viewcontroller from 0 to 1, but doesn't do so if you swipe too fast.
import UIKit
class WizardPageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
lazy var orderedViewControllers: [UIViewController] = {
return [self.newVc(viewController: "intro"),
self.newVc(viewController: "welcome")]
}()
var pageControl = UIPageControl()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
configurePageControl()
// This sets up the first view that will show up on our page control
if let firstViewController = orderedViewControllers.first {
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!
}
func newVc(viewController: String) -> UIViewController {
return UIStoryboard(name: "Wizard", bundle: nil).instantiateViewController(withIdentifier: viewController)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 225,width: UIScreen.main.bounds.width,height: 50))
self.pageControl.numberOfPages = orderedViewControllers.count
self.pageControl.currentPage = 0
pageControl.isEnabled = false
//self.pageControl.tintColor = UIColor.black
self.pageControl.pageIndicatorTintColor = UIColor.gray
self.pageControl.currentPageIndicatorTintColor = UIColor(red:0.647, green:0.192, blue:0.216, alpha:1.00)
self.view.addSubview(pageControl)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
print(orderedViewControllers.index(of: viewController))
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 nil
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
print(orderedViewControllers.index(of: viewController)) // Returns 0 is I swipe too fast, otherwise 1
if let vc = orderedViewControllers[viewControllerIndex] as? WelcomeViewController {
vc.delegate = self
}
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 nil
// Uncommment the line below, remove the line above if you don't want the page control to loop.
// return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
I've encountered exactly the same problem. It essentially boils down to UIPageViewController (_UIQueuingScrollView to be exact) not updating its view hierarchy correctly.
I noticed UIPageViewController is clever enough not to add/remove the content view if the page remains the same (even if it's in wrong place in the view hierarchy it somehow manages to cope with it so it looks good to the user). That's why I added a PageTrackingView to observe the content view being added (or not) to UIPageViewController view hierarchy. By tracking if the change happens I can calculate the current index by flipping it. So currently the workaround is good enough for 2 pages only.
class PageTrackingView: UIView {
var pageIndexable: PageIndexable?
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if var pageIndexable = pageIndexable {
let newIndex = (pageIndexable.internalIndex == 0) ? 1 : 0
pageIndexable.internalIndex = newIndex
}
//Reset pageIndexable so that the index flip is fired only once
pageIndexable = nil
}
}
protocol PageIndexable {
var internalIndex: Int { get set }
}
class PageViewController: UIPageViewController,
UIPageViewControllerDataSource,
UIPageViewControllerDelegate,
PageIndexable {
private var supportedViewControllers = [UIViewController]()
internal var internalIndex: Int = 0 {
didSet {
if supportedViewControllers.indices.contains(internalIndex) {
//Do something with the actual internalIndex value
} else {
assertionFailure()
}
}
init(transitionStyle style: UIPageViewControllerTransitionStyle = .scroll,
navigationOrientation: UIPageViewControllerNavigationOrientation = .horizontal,
options: [String: Any]? = nil,
viewControllers: [T]) {
supportedViewControllers = viewControllers
if !supportedViewControllers.isEmpty {
let viewController = supportedViewControllers[0]
let trackingView = PageTrackingView(frame: viewController.view.frame)
viewController.view.frame = viewController.view.bounds
trackingView.addSubview(viewController.view)
viewController.view = trackingView
}
super.init(transitionStyle: style,
navigationOrientation: navigationOrientation,
options: options)
}
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
if !supportedViewControllers.isEmpty, let trackingView = supportedViewControllers[0].view as? PageTrackingView {
trackingView.pageIndexable = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
datasource = self
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = arrayVCs.index(of: viewController) else {
return nil
}
if index == 0 {
return nil
}
let prevIndex = abs((index - 1) % arrayVCs.count)
return arrayVCs[prevIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = arrayVCs.index(of: viewController) else {
return nil
}
if index == arrayVCs.count - 1 {
return nil
}
let nextIndex = abs((index + 1) % arrayVCs.count)
return arrayVCs[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let viewController = pageViewController.viewControllers?[0] {
guard let index = arrayVCs.index(of: viewController) else {
return
}
self.segment.selectedSegmentIndex = index
}
}
Try this. It's work for me.

Why won't my index reach higher than 1?

I am trying to use PageViewController to generate new ViewControllers with data based on an array of names held in UserDefaults. When the user adds a new name into the array, the PageView should generate a new page on each swipe until the index is >= than the array.count.
The problem is while there are 5 items in the Array, I am able to swipe infinitely, the index works correctly for the first two pages, but it stays at 1 on each next swipe, so it never becomes == or >= so that it will return Nil. The array seems to be correct, when printing it prints the 5 names, but for some reason it is not indexing correctly in the pageView, can anyone Identify what the issue may be?
I hope this is enough information, Manager is the class where i hold the array called coins which contains at the moment 5 names of cryptocurrencies, the idea is to be able to add a new page, appending the array, and so that the pageView will generate a new page retrieving the data from an API to load the specific data for that coin, Very similar to the way the IOS weather app works. Thank you for the help, here is the code of the pageViewController:
import UIKit
class PageViewController: UIPageViewController,
UIPageViewControllerDataSource, UIPageViewControllerDelegate {
//page Control dots
var pageControl = UIPageControl()
func configurePageControl() {
// The total number of pages that are available is based on how
many available colors we have.
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
self.pageControl.numberOfPages = (Manager.shared.coins.count)
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.black
self.pageControl.pageIndicatorTintColor = UIColor.gray
self.pageControl.currentPageIndicatorTintColor = UIColor.white
self.view.addSubview(pageControl)
}
// MARK: Delegate functions
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let pageContentViewController = pageViewController.viewControllers![0]
self.pageControl.currentPage = (viewControllers?.index(of: pageContentViewController)!)!
}
func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> TemplateViewController? {
if Manager.shared.coins.count == 0 || index >= Manager.shared.coins.count {
return nil
}
let templateViewController = storyboard.instantiateViewController(withIdentifier: "templateController") as! TemplateViewController
templateViewController.dataObject = Manager.shared.coins[index]
print(Manager.shared.coins)
return templateViewController
}
func indexOfViewController(_ viewController: TemplateViewController) -> Int {
print(viewController.dataObject)
return Manager.shared.coins.index(of: viewController.dataObject) ?? NSNotFound
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! TemplateViewController)
if (index == 0) || (index == NSNotFound){
return nil
}
index -= 1
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! TemplateViewController)
if index == NSNotFound {
return nil
}
index += 1
if index == Manager.shared.coins.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
//List of View Controllers.
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
configurePageControl()
self.dataSource = self
if let firstViewController = viewControllerAtIndex(0, storyboard: self.storyboard!){
self.setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil)
}
}
}
Coins:
class Manager {
var coins = [""]
let defaults = UserDefaults.standard
static let shared = Manager()
init() {
self.coins = self.defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
}
func addCoin(coin:String) {
self.coins.append(coin)
self.defaults.set(self.coins, forKey: "SavedStringArray")
print ("coins from addCoin:")
print (self.coins)
}
}
and I add coins to the array from elsewhere like so:
#IBAction func goButton(_ sender: Any) {
self.choosePerm()
Manager.shared.coins.append(chosenCoin)
Manager.shared.addCoin(coin: chosenCoin)
print(Manager.shared.coins)
print(chosenCoin)
}
Edit: Above I've edited the way i append the array, choosePerm() gets the name of the coin after searching has been done, and chosenCoin is the coin chosen after search, it definitely is 1 name, but I am still getting it to append double each time, can you see anything In there that might be causing that? i.e. it prints
["Ethereum", "Boolberry", "Boolberry", "Bitcoin", "Bitcoin"]
You are appending the coin twice:
Manager.shared.coins.append(chosenCoin) // <-- appending for the first time
Manager.shared.addCoin(coin: chosenCoin) // <-- appending for the second time
func addCoin(coin:String) {
self.coins.append(coin) // <-- this is the second appending
This kind of error can be fixed but not allowing appending from outside the Manager class:
private(set) var coins = [""]

Data source methods of UIPageViewController are not called

I have the following code in my iOS app:
class BannerTableViewCell: UITableViewCell, UIPageViewControllerDataSource {
private var pageViewController: UIPageViewController!
private var pages: [UIViewController] = []
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clearColor()
self.backgroundView?.backgroundColor = UIColor.clearColor()
self.contentView.backgroundColor = UIColor.clearColor()
self.selectionStyle = UITableViewCellSelectionStyle.None
pageViewController = UIPageViewController();
self.pageViewController.dataSource = self
pageViewController.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 130)
self.addSubview(pageViewController.view)
//Example data
let v1 = UIViewController()
v1.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 130);
v1.view.backgroundColor = UIColor.blueColor()
let v2 = UIViewController()
v2.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 130);
v2.view.backgroundColor = UIColor.greenColor()
pages.append(v1)
pages.append(v2)
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = pages.indexOf(viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard pages.count > previousIndex else {
return nil
}
return pages[previousIndex]
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = pages.indexOf(viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = pages.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return pages[nextIndex]
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pages.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
I instantiate this cell in the table view, however page view controller in this cell is always empty, and the data source methods of pageViewController are not called. Do you have any idea why they are not called?
You should use the documented initializer to instantiate the UIPageViewController:
public init(transitionStyle style: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : AnyObject]?)
Also the ViewControllers you create at the end of awakeFromNib can be placed into the pageViewController right away.
pageViewController.setViewControllers([v1, v2], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
A page indicator will be visible if both methods are implemented, transition style is 'UIPageViewControllerTransitionStyleScroll', and navigation orientation is 'UIPageViewControllerNavigationOrientationHorizontal'.
Both methods are called in response to a 'setViewControllers:...' call, but the presentation index is updated automatically in the case of gesture-driven navigation.
It could also be because the Page View Controller is not your Root View Controller.
You could add the following code in your segue:
let x = (UIApplication.shared.delegate as! AppDelegate).window!
x.rootViewController = yourViewController()

How to change position of UIPageControl in iOS >=8.0?

I have a simple UIPageViewController which displays the default UIPageControl at the bottom of the pages. I wonder if it's possible to modify the position of the UIPageControl, e.g. to be on top of the screen instead of the bottom.
I've been looking around and only found old discussions that say I need to create my own UIPageControl.
Is this thing simpler with iOS8 and 9?
Thanks.
Yes, you can add custom page controller for that.
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)]; // your position
[self.view addSubview: self.pageControl];
then remove
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController
and
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController
Then add another delegate method:
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers
{
PageContentViewController *pageContentView = (PageContentViewController*) pendingViewControllers[0];
self.pageControl.currentPage = pageContentView.pageIndex;
}
Just lookup PageControl in PageViewController subclass and set frame, location or whatever you want
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for subView in view.subviews {
if subView is UIPageControl {
subView.frame.origin.y = self.view.frame.size.height - 164
}
}
}
Override the viewDidLayoutSubviews() of the pageviewcontroller and use this
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// get pageControl and scroll view from view's subviews
let pageControl = view.subviews.filter{ $0 is UIPageControl }.first! as! UIPageControl
let scrollView = view.subviews.filter{ $0 is UIScrollView }.first! as! UIScrollView
// remove all constraint from view that are tied to pagecontrol
let const = view.constraints.filter { $0.firstItem as? NSObject == pageControl || $0.secondItem as? NSObject == pageControl }
view.removeConstraints(const)
// customize pagecontroll
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.addConstraint(pageControl.heightAnchor.constraintEqualToConstant(35))
pageControl.backgroundColor = view.backgroundColor
// create constraints for pagecontrol
let leading = pageControl.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor)
let trailing = pageControl.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor)
let bottom = pageControl.bottomAnchor.constraintEqualToAnchor(scrollView.topAnchor, constant:8) // add to scrollview not view
// pagecontrol constraint to view
view.addConstraints([leading, trailing, bottom])
view.bounds.origin.y -= pageControl.bounds.maxY
}
The Shameerjan answer is very good, but it needs one more thing to work properly, and that is implementation of another delegate method:
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
// If user bailed our early from the gesture,
// we have to revert page control to previous position
if !completed {
let pageContentView = previousViewControllers[0] as! PageContentViewController;
self.pageControl.currentPage = pageContentView.pageIndex;
}
}
This is because if you don't, if you move the page control just so slightly, it will go back to previous position - but the page control will show different page.
Hope it helps!
Swift 4 version of #Jan's answer with fixed bug when the user cancels transition:
First, you create custom pageControl:
let pageControl = UIPageControl()
You add it to the view and position it as you want:
self.view.addSubview(self.pageControl)
self.pageControl.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.pageControl.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 43),
self.pageControl.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -33)
])
Then you need to initialize the pageControl:
self.pageControl.numberOfPages = self.dataSource.controllers.count
Finally, you need to implement UIPageViewControllerDelegate, and its method pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:):
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
// this will get you currently presented view controller
guard let selectedVC = pageViewController.viewControllers?.first else { return }
// and its index in the dataSource's controllers (I'm using force unwrap, since in my case pageViewController contains only view controllers from my dataSource)
let selectedIndex = self.dataSource.controllers.index(of: selectedVC)!
// and we update the current page in pageControl
self.pageControl.currentPage = selectedIndex
}
Now in comparison with #Jan's answer, we update self.pageControl.currentPage using pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) (shown above), instead of pageViewController(_:willTransitionTo:). This overcomes the problem of cancelled transition - pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) is called always when a transition was completed (it also better mimics the behavior of standard page control).
Finally, to remove the standard page control, be sure to remove implementation of presentationCount(for:) and presentationIndex(for:) methods of the UIPageViewControllerDataSource - if the methods are implemented, the standard page control will be presented.
So, you do NOT want to have this in your code:
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.dataSource.controllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
For swift:
self.pageController = UIPageControl(
frame: CGRect(
x: 0,
y: self.view.frame.size.height - 50,
width: self.view.frame.size.width,
height: 50
)
)
self.view.addSubview(pageController)
remember use pageController.numberOfPages and delegate the pageView
then remove
func presentationCountForPageViewController(
pageViewController: UIPageViewController
) -> Int
and
func presentationIndexForPageViewController(
pageViewController: UIPageViewController
) -> Int
Then add another delegate method:
func pageViewController(
pageViewController: UIPageViewController,
willTransitionToViewControllers pendingViewControllers:[UIViewController]){
if let itemController = pendingViewControllers[0] as? PageContentViewController {
self.pageController.currentPage = itemController.pageIndex
}
}
}
Yes, the Shameerjan answer is very good, but instead of adding another page control you can use default page indicator:
- (UIPageControl*)pageControl {
for (UIView* view in self.view.subviews) {
if ([view isKindOfClass:[UIPageControl class]]) {
//set new pageControl position
view.frame = CGRectMake( 100, 200, width, height);
return (id)view;
}
}
return nil;
}
and then extend the size of the UIPageViewController to cover up the bottom gap:
//somewhere in your code
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+40);
here s a very effective way to change the position of the default PageControl for the PageViewController without having the need to create a new one ...
extension UIPageViewController {
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for subV in self.view.subviews {
if type(of: subV).description() == "UIPageControl" {
let pos = CGPoint(x: subV.frame.origin.x, y: subV.frame.origin.y - 75 * 2)
subV.frame = CGRect(origin: pos, size: subV.frame.size)
}
}
}
}
Here's my take. This version only changes de indicator when the animation is finished, i.e. when you get to the destination page.
/** Each page you add to the UIPageViewController holds its index */
class Page: UIViewController {
var pageIndex = 0
}
class MyPageController : UIPageViewController {
private let pc = UIPageControl()
private var pendingPageIndex = 0
// ... add pc to your view, and add Pages ...
/** Will transition, so keep the page where it goes */
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController])
{
let controller = pendingViewControllers[0] as! Page
pendingPageIndex = controller.pageIndex
}
/** Did finish the transition, so set the page where was going */
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
{
if (completed) {
pc.currentPage = pendingPageIndex
}
}
}
Swift 5 & iOS 13.5 (with Manual Layout)
The example below uses a custom UIPageControl, laid out at the bottom center position of the UIPageViewController. To use the code, replace MemberProfilePhotoViewController with the type of view controller you are using as pages.
Quick Notes
You must set the numberOfPages property on pageControl.
To size pageControl you can use pageControl.size(forNumberOfPages: count).
Make sure you delete presentationCount(...) and presentationIndex(...) to remove the default page control.
Using UIPageViewControllerDelegate's didFinishAnimating seems to be better timing for updating pageControl.currentPage.
The Code
import Foundation
import UIKit
class MemberProfilePhotosViewController: UIPageViewController {
private let profilePhotoURLs: [URL]
private let profilePhotoViewControllers: [MemberProfilePhotoViewController]
private var pageControl: UIPageControl?
// MARK: - Initialization
init(profilePhotoURLs: [URL]) {
self.profilePhotoURLs = profilePhotoURLs
profilePhotoViewControllers = profilePhotoURLs.map { (profilePhotoURL) -> MemberProfilePhotoViewController in
MemberProfilePhotoViewController(profilePhotoURL: profilePhotoURL)
}
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
// MARK: UIViewController
override func loadView() {
super.loadView()
pageControl = UIPageControl(frame: CGRect.zero)
pageControl!.numberOfPages = profilePhotoViewControllers.count
self.view.addSubview(pageControl!)
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
if let firstViewController = profilePhotoViewControllers.first {
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let pageControl = pageControl {
let pageControlSize = pageControl.size(forNumberOfPages: profilePhotoViewControllers.count)
pageControl.frame = CGRect(
origin: CGPoint(x: view.frame.midX - pageControlSize.width / 2, y: view.frame.maxY - pageControlSize.height),
size: pageControlSize
)
}
}
// MARK: Private Helpers
private func indexOf(_ viewController: UIViewController) -> Int? {
return profilePhotoViewControllers.firstIndex(of: viewController as! MemberProfilePhotoViewController)
}
}
extension MemberProfilePhotosViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
guard let selectedViewController = pageViewController.viewControllers?.first else { return }
if let indexOfSelectViewController = indexOf(selectedViewController) {
pageControl?.currentPage = indexOfSelectViewController
}
}
}
extension MemberProfilePhotosViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = profilePhotoViewControllers.firstIndex(of: viewController as! MemberProfilePhotoViewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard profilePhotoViewControllers.count > previousIndex else {
return nil
}
return profilePhotoViewControllers[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = profilePhotoViewControllers.firstIndex(of: viewController as! MemberProfilePhotoViewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let profilePhotoViewControllersCount = profilePhotoViewControllers.count
guard profilePhotoViewControllersCount != nextIndex else {
return nil
}
guard profilePhotoViewControllersCount > nextIndex else {
return nil
}
return profilePhotoViewControllers[nextIndex]
}
}
This is good, and with more change
var pendingIndex = 0;
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
pageControl.currentPage = pendingIndex
}
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
let itemController = pendingViewControllers.first as! IntroPageItemViewController
pendingIndex = itemController.itemIndex
}
Make sure pageControl is added as subview.
Then in
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGRect frame = self.pageControl.frame;
frame.origin.x = self.view.frame.size.width/2 -
frame.size.width/2;
frame.origin.y = self.view.frame.size.height - 100 ;
self.pageControl.numberOfPages = self.count;
self.pageControl.currentPage = self.currentIndex;
self.pageControl.frame = frame;
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for view in self.view.subviews{
if view is UIScrollView{
view.frame = UIScreen.main.bounds
}
else if view is UIPageControl {
view.backgroundColor = UIColor.clear
view.frame.origin.y = self.view.frame.size.height - 75
}
}
}
Just get the first view controller and find out the index in didFinishAnimating:
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
pageControl.currentPage = onboardingViewControllers.index(of: pageViewController.viewControllers!.first!)!
}

Resources