Reputation: 79
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
Reputation: 1349
Check out this answer
Things have been pretty much the same over these years:
UIScrollView
delegate to your view controller (which you did);scrollViewDidScroll
delegate method:func scrollViewDidScroll(_ scrollView: UIScrollView)
{
self.pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x / scrollView.width)))
}
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