[iOS] - Page Control

Din의 개발노트·2021년 3월 8일
1

1. Page Control

Page Control을 활용해서 스크롤되는 UI를 알아보도록 하겠습니다.

  1. Collection View를 만들고 페이지를 이동할때마다 페이지 컨트롤을 업데이트 하는 기능은 UIScrollViewDelegate를 채용하고 페이지 컨트롤을 스크롤할때마다 현재 페이지를 계산해서 현재페이지에 저장해야합니다.

  2. 페이지 컨트롤을 탭할때 해당 컨트롤로 이동하는 방법은 value changed 이벤트를 이용해서 구현합니다.

Code

import UIKit

class ViewController: UIViewController {
    
    var imgName = ["1번", "2번", "3번", "4번", "5번"]
   
    @IBOutlet weak var listCollectionView: UICollectionView!
    @IBOutlet weak var pager: UIPageControl!
    
    @IBAction func pageChanged(_ sender: UIPageControl) {
        let indexPath = IndexPath(item: sender.currentPage, section: 0)
        listCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 초기화 구현
        pager.numberOfPages = imgName.count
        // 현재 페이지
        pager.currentPage = 0
        
        // 페이지 컬러 속성 변경
        pager.pageIndicatorTintColor = UIColor.gray
        pager.currentPageIndicatorTintColor = UIColor.red
    }
}

extension ViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) { // 컬렉션뷰를 스크롤하면 반복적으로 호출
        let width = scrollView.bounds.size.width // 너비 저장
        let x = scrollView.contentOffset.x + (width / 2.0) // 현재 스크롤한 x좌표 저장
        
        let newPage = Int(x / width)
        if pager.currentPage != newPage {
            pager.currentPage = newPage
        }
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgName.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? ListCell else {
            return UICollectionViewCell()
        }
        let img = UIImage(named: "\(imgName[indexPath.item]).jpeg")
        cell.imgView.image = img

        return cell
    }
}

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.bounds.size
    }
}

class ListCell: UICollectionViewCell {
    @IBOutlet weak var imgView: UIImageView!
}

profile
iOS Develpoer

0개의 댓글