[IOS / Swift] 배너 자동 슬라이드 (with - UICollectionView)

서프로·2023년 3월 31일
0
post-thumbnail

오늘은 자동 슬라이드가 되는 배너를 만들어 보겠음.

UICollectionView를 사용하는 방법 외에도 다른 방법이 있겠지만 이 글에선 UICollectionView를 사용함.

먼저 먼저 스토리보드에 CollectionView를 추가 해준 뒤 Constraints 설정을 함.

이 글에선 top, leading, trailing 을 0으로 주고 Height를 28만큼 주겠음.



원하는 스크롤 방향을 선택하고 Estimate Size는 None을 선택.
후에 코드로 사이즈를 정의할 것임.

이어서 스토리보드 Collection View Cell 안에 UILabel을 넣은 후 Constraints를 설정.


Cell Class를 하나 만들고 스토리보드에서 생성했던 UILabel을 IBOutlet으로 설정.

각각의 인스펙터에서 위와 같이 BannerCell 클래스와 Identifier를 설정.

@IBOutlet weak var uiCollectionView: UICollectionView!
    
var currentPage: Int = 0
let headerArray = ["첫 번째 슬라이드", "두 번째 슬라이드", "세 번째 슬라이드"]

ViewController에 CollectionView를 연결 시켜주고, 현재 페이지를 나타낼 변수 하나와, 배너 UILabel에 들어갈 String 배열을 선언.

override func viewDidLoad() {
	super.viewDidLoad()
       
    uiCollectionView.delegate = self
    uiCollectionView.dataSource = self
}

델리게이트와 데이터소스를 누가 처리할건지 써줌.

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
	//Collection View 개수 설정
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return headerArray.count
    }
    // CollectionViewCell 설정
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = uiCollectionView.dequeueReusableCell(withReuseIdentifier: "BannerCell", for: indexPath) as! BannerCell
        cell.bannerLabel.text = headerArray[indexPath.row]
        
        return cell
    }
    // CollectionViewCell Size 설정
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: uiCollectionView.frame.width, height: uiCollectionView.frame.height)
    }
    
}

UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayoutextension으로 따로 분리해서 작성해줌.

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        uiCollectionView.delegate = self
        uiCollectionView.dataSource = self
        
        startTimer()
    }
    
    // 3초마다 실행되는 타이머
    func startTimer() {
        let _: Timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { (Timer) in
            self.bannerMove()
        }
    }
    // 배너 움직이는 매서드
    func bannerMove() {
        // 현재페이지가 마지막 페이지일 경우
        if currentPage == headerArray.count-1 {
            // 맨 처음 페이지로 돌아감
            uiCollectionView.scrollToItem(at: NSIndexPath(item: 0, section: 0) as IndexPath, at: .right, animated: true)
            currentPage = 0
            return
        }
        // 다음 페이지로 전환
        currentPage += 1
        uiCollectionView.scrollToItem(at: NSIndexPath(item: currentPage, section: 0) as IndexPath, at: .right, animated: true)
    }

마지막으로 위의 함수를 만들어 viewDidLoad에 넣어주면 정상적으로 자동 슬라이드 되는 배너를 볼 수 있음.

0개의 댓글