46

I am trying to create a Page View controller with numbers of view. I want a simple code sample that will use UIPageViewController.

Cœur
  • 37,241
  • 25
  • 195
  • 267
LC 웃
  • 18,888
  • 9
  • 57
  • 72
  • You can use https://github.com/barankaraoguzzz/FastOnBoarding for easy work. Pleas try it. – Baran Karaoğuz Apr 18 '17 at 10:28
  • 2
    This is not a forum to get ready made solutions or answers. Instead show your efforts and what did you try and then ask for solutions where you are facing problem. Entire solutions are not encouraged. – Tejas Jun 04 '18 at 11:30
  • @Tejas Answering your own question is encouraged on SO so that it might help for future readers. – LC 웃 Jun 04 '18 at 16:56
  • 1
    @Anish웃 Agreed. Answering your own question is encouraged. But asking for a end-to-end solution without own efforts is not encouraged. – Tejas Jun 05 '18 at 06:31

5 Answers5

135
import UIKit

class DummyVC: UIViewController, UIScrollViewDelegate {

    let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
    var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
    var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
    var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))    

    override func viewDidLoad() {
        super.viewDidLoad()

        configurePageControl()

        scrollView.delegate = self
        scrollView.isPagingEnabled = true

        self.view.addSubview(scrollView)
        for index in 0..<4 {

            frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
            frame.size = self.scrollView.frame.size

            let subView = UIView(frame: frame)
            subView.backgroundColor = colors[index]
            self.scrollView .addSubview(subView)
        }

        self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
        pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

    }

    func configurePageControl() {
        // The total number of pages that are available is based on how many available colors we have.
        self.pageControl.numberOfPages = colors.count
        self.pageControl.currentPage = 0
        self.pageControl.tintColor = UIColor.red
        self.pageControl.pageIndicatorTintColor = UIColor.black
        self.pageControl.currentPageIndicatorTintColor = UIColor.green
        self.view.addSubview(pageControl)

    }

    // MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
    func changePage(sender: AnyObject) -> () {
        let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
        scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = Int(pageNumber)
    }

}
nacho4d
  • 43,720
  • 45
  • 157
  • 240
LC 웃
  • 18,888
  • 9
  • 57
  • 72
  • @anishparajuli: would you please have a look to: href="http://stackoverflow.com/questions/36174529/swift-scrollview-with-paging-for-slideshow-displays-some-initial-images-in-the – SagittariusA Mar 23 '16 at 14:52
  • I have followed this tutorial (https://www.raywenderlich.com/76436/use-uiscrollview-scroll-zoom-content-swift) which very similar to your code but I can't make it work – SagittariusA Mar 23 '16 at 14:53
  • i'm using this method in a `UIView` class. Have very problems with this `var frame: CGRect = CGRectMake(0, 0, 0, 0)`. this name `frame` should not use, rename for other. `frame` cause conflicts with `self.frame` – jose920405 May 04 '16 at 21:23
  • Your code helped enormously. I tried taking the next step. http://stackoverflow.com/questions/40996685/in-uiscrollview-uiview-displays-successive-frame-information-correctly-while-uil – Greg Dec 07 '16 at 02:18
35

For lazy coder this is the Swift 3 implementation based on That lazy iOS Guy 웃's answer

import UIKit

class ViewController: UIViewController,UIScrollViewDelegate {

    let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
    var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
    var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        configurePageControl()

        scrollView.delegate = self
        self.view.addSubview(scrollView)
        for index in 0..<4 {

            frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
            frame.size = self.scrollView.frame.size

            let subView = UIView(frame: frame)
            subView.backgroundColor = colors[index]
            self.scrollView .addSubview(subView)
        }
        self.scrollView.isPagingEnabled = true
        self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * 4, height: self.scrollView.frame.size.height)
        pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

    }

    func configurePageControl() {
        // The total number of pages that are available is based on how many available colors we have.
        self.pageControl.numberOfPages = colors.count
        self.pageControl.currentPage = 0
        self.pageControl.tintColor = UIColor.red
        self.pageControl.pageIndicatorTintColor = UIColor.black
        self.pageControl.currentPageIndicatorTintColor = UIColor.green
        self.view.addSubview(pageControl)

    }

    // MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
    func changePage(sender: AnyObject) -> () {
        let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
        scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = Int(pageNumber)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
Community
  • 1
  • 1
John Lim
  • 3,019
  • 4
  • 31
  • 41
  • 8
    Great answer! For Swift 3, we should change Selector(("changePage:")) to #selector(self.changePage(sender:)) – jeantimex Nov 10 '16 at 06:29
  • 4
    `self.scrollView.isPagingEnabled = true` should be *outside* the for loop – ThunderStruct Jan 28 '17 at 15:10
  • 1
    This code does not work correctly because the scrollview frame is not yet correct if you are working with AutoLayout. Make sure to add scrollView.setNeedsLayout() or scrollView.layoutIfNeeded() – Adriana Oct 31 '17 at 10:13
7

Swift 3 - Horizontal image scroll

import UIKit

class pageenabled: UIViewController,UIScrollViewDelegate 
{
    let imagelist = ["img1.jpg", "photo1.jpg", "photo3.jpg", "photo4.jpg", "photo5.jpg"]
    var scrollView = UIScrollView()

    var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))

    var yPosition:CGFloat = 0
    var scrollViewContentSize:CGFloat=0;

    override func viewDidLoad() {
        super.viewDidLoad()

        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300))

        configurePageControl()

        scrollView.delegate = self
        self.view.addSubview(scrollView)
        for  i in stride(from: 0, to: imagelist.count, by: 1) {
            var frame = CGRect.zero
            frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
            frame.origin.y = 0
            frame.size = self.scrollView.frame.size
            self.scrollView.isPagingEnabled = true

            let myImage:UIImage = UIImage(named: imagelist[i])!
            let myImageView:UIImageView = UIImageView()
            myImageView.image = myImage
            myImageView.contentMode = UIViewContentMode.scaleAspectFit
            myImageView.frame = frame

            scrollView.addSubview(myImageView)
        }

        self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(imagelist.count), height: self.scrollView.frame.size.height)
        pageControl.addTarget(self, action: Selector(("changePage:")), for: UIControlEvents.valueChanged)
        // Do any additional setup after loading the view.
    }
    func configurePageControl() {
        // The total number of pages that are available is based on how many available colors we have.
        self.pageControl.numberOfPages = imagelist.count
        self.pageControl.currentPage = 0
        self.pageControl.tintColor = UIColor.red
        self.pageControl.pageIndicatorTintColor = UIColor.black
        self.pageControl.currentPageIndicatorTintColor = UIColor.green
        self.view.addSubview(pageControl)

    }

    // MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
    func changePage(sender: AnyObject) -> () {
        let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
        scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = Int(pageNumber)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Manee ios
  • 1,112
  • 11
  • 14
3

In Swift 3.0 craeate iboutlets through story board for scrollview and pagecontroller.

@IBOutlet weak var imgScrollView: UIScrollView!
@IBOutlet weak var imgPageController: UIPageControl!
var sliderImagesArray = NSMutableArray()

in viewdidload method write this code

sliderImagesArray = ["https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080","https://images.unsplash.com/photo-1447746249824-4be4e1b76d66?w=1080", "https://images.unsplash.com/photo-1463595373836-6e0b0a8ee322?w=1080"]
    imgScrollView.delegate = self
for i in 0..<sliderImagesArray.count {
        var imageView : UIImageView
        let xOrigin = self.imgScrollView.frame.size.width * CGFloat(i)
        imageView = UIImageView(frame: CGRect(x: xOrigin, y: 0, width: self.imgScrollView.frame.size.width, height: self.imgScrollView.frame.size.height))
        imageView.isUserInteractionEnabled = true
        let urlStr = sliderImagesArray.object(at: i)
        print(imgScrollView,imageView, urlStr)
        imageView.sd_setImage(with: URL(string: urlStr as! String), placeholderImage: UIImage(named: "placeholder.png"))
        imageView .contentMode = UIViewContentMode.scaleToFill
        self.imgScrollView.addSubview(imageView)
    }
    self.imgScrollView.isPagingEnabled = true
    self.imgScrollView.bounces = false
    self.imgScrollView.showsVerticalScrollIndicator = false
    self.imgScrollView.showsHorizontalScrollIndicator = false
    self.imgScrollView.contentSize = CGSize(width: 
    self.imgScrollView.frame.size.width * CGFloat(sliderImagesArray.count), height: self.imgScrollView.frame.size.height)
    imgPageController.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

    self.imgPageController.numberOfPages = sliderImagesArray.count
    self.imgPageController.currentPage = 0
    self.imgPageController.tintColor = UIColor.red
    self.imgPageController.pageIndicatorTintColor = UIColor.black
    self.imgPageController.currentPageIndicatorTintColor = UIColor.blue

after that implement scrollview delegate methods

func changePage(sender: AnyObject) -> () {
    let x = CGFloat(imgPageController.currentPage) * imgScrollView.frame.size.width
    imgScrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(imgScrollView.contentOffset.x / imgScrollView.frame.size.width)
    imgPageController.currentPage = Int(pageNumber)
}
User558
  • 1,165
  • 1
  • 13
  • 37
0
       @IBOutlet weak var scrollView: UIScrollView! 
@IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!

extension ZoomedPhotoViewController: UIScrollViewDelegate {
  func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return imageView
  }
}
private func updateMinZoomScaleForSize(size: CGSize) {
  let widthScale = size.width / imageView.bounds.width
  let heightScale = size.height / imageView.bounds.height
  let minScale = min(widthScale, heightScale)  

  scrollView.minimumZoomScale = minScale 

  scrollView.zoomScale = minScale
}


override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()

  updateMinZoomScaleForSize(view.bounds.size)
}

private func updateConstraintsForSize(size: CGSize) {   

  let yOffset = max(0, (size.height - imageView.frame.height) / 2) 
  imageViewTopConstraint.constant = yOffset
  imageViewBottomConstraint.constant = yOffset

  let xOffset = max(0, (size.width - imageView.frame.width) / 2)
  imageViewLeadingConstraint.constant = xOffset
  imageViewTrailingConstraint.constant = xOffset

  view.layoutIfNeeded()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
  updateConstraintsForSize(view.bounds.size) 
}

import UIKit

public class PhotoCommentViewController: UIViewController {  
  @IBOutlet weak var imageView: UIImageView!
  @IBOutlet weak var scrollView: UIScrollView!
  @IBOutlet weak var nameTextField: UITextField!
  public var photoName: String!

  override public func viewDidLoad() {
    super.viewDidLoad()
    if let photoName = photoName {
      self.imageView.image = UIImage(named: photoName)
    }
  }
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if let cell = sender as? UICollectionViewCell,
      indexPath = collectionView?.indexPathForCell(cell),
      photoCommentViewController = segue.destinationViewController as? PhotoCommentViewController {
    photoCommentViewController.photoName = "photo\(indexPath.row + 1)"
  }
}
NSNotificationCenter.defaultCenter().addObserver(
  self,
  selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)),
  name: UIKeyboardWillShowNotification,
  object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
  self,
  selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)),
  name: UIKeyboardWillHideNotification,
  object: nil
) 
deinit {
  NSNotificationCenter.defaultCenter().removeObserver(self)
}

func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
  guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
  let keyboardFrame = value.CGRectValue()
  let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1)
  scrollView.contentInset.bottom += adjustmentHeight
  scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}

func keyboardWillShow(notification: NSNotification) {
  adjustInsetForKeyboardShow(true, notification: notification)
}

func keyboardWillHide(notification: NSNotification) {
  adjustInsetForKeyboardShow(false, notification: notification)
}  
@IBAction func hideKeyboard(sender: AnyObject) {
  nameTextField.endEditing(true)
}
public var photoIndex: Int!



import UIKit

class ManagePageViewController: UIPageViewController {
  var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
  var currentIndex: Int!

  override func viewDidLoad() {
    super.viewDidLoad()

    dataSource = self

    // 1
    if let viewController = viewPhotoCommentController(currentIndex ?? 0) {
      let viewControllers = [viewController]
      // 2
      setViewControllers(
        viewControllers,
        direction: .Forward,
        animated: false,
        completion: nil
      )
    }
  }

  func viewPhotoCommentController(index: Int) -> PhotoCommentViewController? {
    if let storyboard = storyboard,
        page = storyboard.instantiateViewControllerWithIdentifier("PhotoCommentViewController") 
        as? PhotoCommentViewController {
      page.photoName = photos[index]
      page.photoIndex = index
      return page
    }
    return nil
  }
}
  • 4
    Hi and welcome! Some explanations would significantly improve the quality of your answer – mrun May 25 '17 at 07:15