iosswiftuicollectionviewuicollectionviewcelluipagecontrol

How to connect UIPageControl and CollectionView?


I have collection view with Custom View Cell. There are scroll view and three image view in a custom view cell.

My ViewController has UIPageControll, but I don't know how to connect UIPageControll and scroll view.

My code

ViewController:

    class MainScrenenViewController: UIViewController {
    
        let data = [
        
            CustomData(title: "A", backgroundImage: #imageLiteral(resourceName: "Onboard")),
            CustomData(title: "B", backgroundImage: #imageLiteral(resourceName: "Onboard")),
            CustomData(title: "B", backgroundImage: #imageLiteral(resourceName: "Onboard")),
        ]
        
        //UIPage Controller
        lazy var pageControl: UIPageControl = {
            let pageControl = UIPageControl()
            pageControl.numberOfPages = data.count
            pageControl.translatesAutoresizingMaskIntoConstraints = false
            pageControl.addTarget(self, action: #selector(pageControlTapHandler(sender:)), for: .touchUpInside)
            return pageControl
        }()
    
        var collectionView: UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectionView.register(DayWeatherCell.self, forCellWithReuseIdentifier: "sliderCell")
            collectionView.layer.cornerRadius = 5
            collectionView.translatesAutoresizingMaskIntoConstraints = false
            collectionView.backgroundColor = UIColor(red: 0.125, green: 0.306, blue: 0.78, alpha: 1)
            return collectionView
        }()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            view.backgroundColor = .brown
            
            view.addSubview(collectionView)
            view.addSubview(pageControl)
            
            collectionView.dataSource = self
            collectionView.delegate = self
            
            setupConstraints()
            
        }
    
        //MARK: ~FUNCTIONS
        
        func setupConstraints() {
            
            let constraints = [
                
                collectionView.widthAnchor.constraint(equalToConstant: 344),
                collectionView.heightAnchor.constraint(equalToConstant: 212),
                collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
                collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
                collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 112),
                
                pageControl.topAnchor.constraint(equalTo: cityLabel.bottomAnchor, constant: 10),
                pageControl.widthAnchor.constraint(equalToConstant: 100),
                pageControl.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            ]
            NSLayoutConstraint.activate(constraints)
        }
        
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
        
        //Selector for UIPage Controller
        @objc func pageControlTapHandler(sender: UIPageControl) {
            //I don't know what I need to do here
        }
    
extension MainScrenenViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data.count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sliderCell", for: indexPath) as! DayWeatherCell
        
        cell.backgroundColor = .red
        
        return cell
    }
    
}

extension MainScrenenViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
           print("User tapped on item \(indexPath.row)")
        }
}

extension MainScrenenViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
}

extension MainScrenenViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    }
}

My CollectionViewCell:

class DayWeatherCell: UICollectionViewCell, UIScrollViewDelegate {
    
    weak var mainScreenViewController: MainScrenenViewController?
    
    var data: CustomData? {
        didSet {
            guard let data = data else { return }
            imageView.image = data.backgroundImage
        }
    }
    
    var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "Onboard")
        imageView.layer.cornerRadius = 5
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        return scrollView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(scrollView)
        contentView.addSubview(imageView)
        
        self.contentView.layer.cornerRadius = 10
        
        let constraints = [
            
            scrollView.topAnchor.constraint(equalTo: contentView.topAnchor),
            scrollView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
            scrollView.rightAnchor.constraint(equalTo: contentView.rightAnchor),
            scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
            
            imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
            imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor),
            imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        ]
        NSLayoutConstraint.activate(constraints)
    }
    
    required init?( coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

enter image description here


Solution

  • You can use this. In this code block, collection view cell size equal to collection view and collection view scroll horizontally. I hope, this helps you.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
            let offSet = scrollView.contentOffset.x
            let width = scrollView.frame.width
            let horizontalCenter = width / 2
            
            pageControl.currentPage = Int(offSet + horizontalCenter) / Int(width)
        }