Swift: Images carousel using a collection view

Jru
6 min readMay 24, 2023

--

[Manual-scrolling]手動版輪播效果

Go to see → Auto-Scrolling 自動輪播

介紹

使用元件:collection view, image view, page control

排版設計:AutoLayout

製作過程

  1. 將Collection View、Image View、page control元件加到 viewController的 storyboard 裡。

2. 用AutoLayout排版要記得將 collection view 的 Estimate Size 改為 None!

page control不要放在collection view裡面,才不會跟著banner一起滑動。AutoLayout排版時先設定水平和垂值對齊,在去條整垂直(Y)的高度。

3. 加入CollectionView Cell檔案,並設置 cell 的 identifier名稱。

拉imageView的IBOutlet到collectionViewCell裡。

4. 在Accets裡加入圖片。

5. ViewController裡撰寫程式碼


import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var bannerCollectionView: UICollectionView!

@IBOutlet weak var pageControl: UIPageControl!

var banners = ["1","2","3"]

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

configureCellSize()

}

func configureCellSize(){
if let layout = bannerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
layout.scrollDirection = .horizontal
}
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
banners.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerCollectionViewCell", for: indexPath) as! BannerCollectionViewCell
let indexPath = banners[indexPath.item]
cell.bannerImageView.contentMode = .scaleAspectFill
cell.bannerImageView.image = UIImage(named: "\(indexPath)")
return cell

}

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

return bannerCollectionView.bounds.size
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentPage = ceil(scrollView.contentOffset.x / scrollView.bounds.size.width)
pageControl.currentPage = Int(currentPage)
pageControl.backgroundStyle = .prominent
pageControl.numberOfPages = banners.count
}
}

--

--