Asad Khatri
Asad Khatri

Reputation: 79

How should i use UIpageControl from UIScrollView

How should I use UIpageControl from UIScrollView? I am stuck, help me out.

Here is my code please help;

class home: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var pagecontrol: UIPageControl!

    var imageArray = [UIImage]()
    var pageControl : UIPageControl!

    override func viewDidLoad() {
        super.viewDidLoad()


        mainScrollView.delegate = self

    imageArray = [#imageLiteral(resourceName: "sliderImage"), #imageLiteral(resourceName: "clothing"), #imageLiteral(resourceName: "sports")]

        for i in 0..<imageArray.count{

            let imageView = UIImageView()
            imageView.image = imageArray[i]
            imageView .contentMode = .scaleToFill
            let xPosition = self.view.frame.width * CGFloat(i)
            imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)

            mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
            mainScrollView.addSubview(imageView)
        }


        // Do any additional setup after loading the view.
    }


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

Upvotes: 0

Views: 729

Answers (1)

alexey.m
alexey.m

Reputation: 1349

Check out this answer

Things have been pretty much the same over these years:

  1. Set your UIScrollView delegate to your view controller (which you did);
  2. Add code for scrollViewDidScroll delegate method:
func scrollViewDidScroll(_ scrollView: UIScrollView) 
{
    self.pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x / scrollView.width)))
}  
  1. Add the same in scrollViewDidEndDecelerating method:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
{
    self.pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x / scrollView.width)))
}

Although, it depends on your needs - try how it works with and without each of them.

Upvotes: 1

Related Questions