透過 UIScrollView 刻出 slider carousel
3 min readApr 14, 2019
輪播圖結構如下

原理
width = scrollView 的寬
height = scrollView 的高
currentImage/otherImage 寬高和 scrollView 的寬高相等

//設置scrollView的contentSize = 3倍的scrollView寬
self.scrollView?.contentSize = CGSize(width: width * 3, height: height)

//預設將otherImage設置在currentImage的左邊otherImage.frame = CGRect(x: 0, y: 0, width: width, height: height)
currentImage.frame = CGRect(x: 0, y: width, width: width, height: height)//設置顯示的位置
self.scrollView!.contentOffset = CGPoint(x: self.bounds.size.width, y: 0)
無限滾動
左右滑動改變 otherImage 的 frame,讓其移至 currentImage 的左右邊,滑動結束後交換兩張圖片的內容,並重置 scrollView 的滾動位置
自動輪播
可以看到這邊是用 GCD 的 DispatchSource Timer,而不是 Timer,考量的點可以看看這篇,就不再多做說明了
接著在 scrollView Delegate ,呼叫上面定義好的 function
以上實現簡單的輪播圖片功能,附上 source code~~