简体   繁体   中英

CollectionView + Page control

I've collectionView where every cell is a page (the cell occupies the whole screen in portrait mode and 2 cells in landscape mode). I'm trying to add the current page number/the total number of pages (ie 1/30) what I got so far 1/0 --> one is the current page number and 0 is the total number of pages.

there are two problems:

  • the total number of pages show up only when I start scrolling
  • when I scroll the current page number doesn't change.

the code I use:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

        if pageControl.currentPage < pages.count {
                   pageControl.currentPage += 1
                    numberOfPagesLabel.text = "\(pageControl.currentPage + 1)/\(pages.count)"
        } else if pageControl.currentPage != 0 {
                    pageControl.currentPage -= 1
                    numberOfPagesLabel.text = "\(pageControl.currentPage - 1)/\(pages.count)"
                }
    }

class DetailsViewController: UIViewController, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate  {

     private var collectionView: UICollectionView!
    
    let pageControl = UIPageControl (frame: CGRect(x: 20, y: 120, width: 44, height: 44))
    let numberOfPagesLabel = UILabel (frame: CGRect(x: 20, y: 0, width: 44, height: 44))

    
    private var pages = [Pages]() {
      didSet {
        DispatchQueue.main.async {
          self.collectionView.reloadData()
        }
      }
    }
    
     override func viewDidLoad() {
         super.viewDidLoad()
      
        numberOfPagesLabel.layer.cornerRadius = 15.0
        numberOfPagesLabel.clipsToBounds = true
        numberOfPagesLabel.center.x = self.view.center.x
        numberOfPagesLabel.center.y = self.view.center.y+350

         
         self.view.addSubview(collectionView)
        self.view.addSubview(pageControl)
        self.view.addSubview(numberOfPagesLabel)

     }

         override func viewDidAppear(_ animated: Bool) {
           super.viewDidAppear(true)
            
            collectionViewLayout()
            collectionView.delegate = self
            collectionView.dataSource = self

            }
  

    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        if pageControl.currentPage < pages.count {
                   pageControl.currentPage += 1
                    numberOfPagesLabel.text = "\(pageControl.currentPage + 1)/\(pages.count)"
        } else if pageControl.currentPage != 0 {
                    pageControl.currentPage -= 1
                    numberOfPagesLabel.text = "\(pageControl.currentPage - 1)/\(pages.count)"
                }
    }
    
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pages.count
         }


     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colCell7", for: indexPath) as! colCell7
        
         let book = pages[indexPath.row]
         cell.setupCell(for: book)
         return cell
     }



     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        if UIWindow.isLandscape {
            return CGSize(width: (collectionView.frame.size.width)/2, height: (collectionView.frame.size.height))
        }

        else {            return CGSize(width: (collectionView.frame.size.width), height: (collectionView.frame.size.height))
        }
    }

    
 func collectionViewLayout() {
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
       collectionView.backgroundColor = .white

       collectionView.showsHorizontalScrollIndicator = false
       collectionView.showsVerticalScrollIndicator = false
       collectionView.isPagingEnabled = true


        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.register(colCell7.self, forCellWithReuseIdentifier: "colCell7")
        collectionView.isScrollEnabled = true
       collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
       layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height)
              layout.minimumLineSpacing = 0
              layout.minimumInteritemSpacing = 0
       layout.itemSize = CGSize(width: view.frame.width/2, height:view.frame.height )
    }
}

try this code for get currentPage in CollectionView:

public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    // for horizontal scroll
    let currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
    
  // for vertical scroll
//    let currentPage = Int(scrollView.contentOffset.y) / Int(scrollView.frame.height)
    
    pageControl.currentPage = currentPage
        
numberOfPagesLabel.text = "\(self.pages.count)/\(self.pageControl.currentPage - 1)"
}

better add calculator code for detect current page in scrollViewDidEndDecelerating function, when scroll end Deceleratin.

complete code:

public struct Pages {
    public var title: String
}

class DetailsViewController: UIViewController, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout  {
    
    private var collectionView: UICollectionView!
    
    let pageControl = UIPageControl (frame: CGRect(x: 20, y: 120, width: 44, height: 44))
    let numberOfPagesLabel = UILabel (frame: CGRect(x: 20, y: 0, width: 44, height: 44))
    
    
    private var pages = [Pages]() {
        didSet {
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.numberOfPagesLabel.textColor = .red
        self.numberOfPagesLabel.backgroundColor = .blue
        
        collectionViewLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        
        self.view.addSubview(collectionView)
        self.view.addSubview(pageControl)
        self.view.addSubview(numberOfPagesLabel)
        
        numberOfPagesLabel.translatesAutoresizingMaskIntoConstraints = false
        numberOfPagesLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
        numberOfPagesLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
        
        
        self.collectionView.register(UINib.init(nibName: "colCell7", bundle: nil), forCellWithReuseIdentifier: "colCell7")
        numberOfPagesLabel.layer.cornerRadius = 15.0
        numberOfPagesLabel.clipsToBounds = true
        numberOfPagesLabel.center.x = self.view.center.x
        numberOfPagesLabel.center.y = self.view.center.y+350
        
        collectionView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        collectionView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        collectionView.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
        collectionView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        
        pages = [.init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),.init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1"),
                 .init(title: "1")]
        
        pageControl.numberOfPages = pages.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pages.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colCell7", for: indexPath) as! colCell7
        
        let book = pages[indexPath.row]
        cell.setupCell(pages: book)
        
        return cell
    }
    
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // for horizontal scroll
        let currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
        
      // for vertical scroll
    //    let currentPage = Int(scrollView.contentOffset.y) / Int(scrollView.frame.height)
        
        pageControl.currentPage = currentPage
            
    numberOfPagesLabel.text = "\(self.pages.count)/\(currentPage)"
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width: (collectionView.frame.size.width), height: (collectionView.frame.size.height))
    }
    
    
    func collectionViewLayout() {
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.isPagingEnabled = true
        
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.isScrollEnabled = true
        layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: view.frame.width/2, height:view.frame.height )
    }
}

output:

在此处输入图像描述

I figured it out. the code below work with landscape orintation (with 2 cells) and portrait orintation (with 1 cell) I still have one problem the counting doesn't appear until the scrolling starts.

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if UIWindow.isLandscape {
            let x = scrollView.contentOffset.x
            let w = scrollView.bounds.size.width/2
            let currentPage = Int(ceil(x/w))
        numberOfPagesLabel.text = "\(self.pages.count)/\(currentPage + 2)"
                        pageControl.currentPage = Int(currentPage)        }
        else
        {
            let x = scrollView.contentOffset.x
            let w = scrollView.bounds.size.width
            let currentPage = Int(ceil(x/w))
        numberOfPagesLabel.text = "\(self.pages.count)/\(currentPage + 1)"
                        pageControl.currentPage = Int(currentPage)
        }
extension UIWindow {
    static var isLandscape: Bool {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.windows
                .first?
                .windowScene?
                .interfaceOrientation
                .isLandscape ?? false
        } else {
            return UIApplication.shared.statusBarOrientation.isLandscape
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM