swift 輪播圖無限滾動 控件的封裝
這篇文章主要記錄自己是怎么一步一步封裝一個 輪播圖, 記錄了整個過程和遇到的一些問題和解決辦法.
我是在 oc 項目中 用swift 寫了一個輪播圖
如何在 oc 項目中
使用 swift 文件 可以看我這篇文章 OC 中 使用 swfit 代碼.
這篇文章給了實現輪播圖的四種思路, 嗯, 我選擇了使用 collectionView 這個思路
下面的思路和代碼都是來自于 使用 collectionView 實現 無限輪播圖
- 使用 collectionView 實現輪播圖
最初的思路, 創建collectionView 有一個section , section中有 n 個items.
這里面有個問題, 就是當滑動到最后一個items 時 怎么回到第一個items 實現無限滑動?
換一種思路, 設置 3 個 section
默認顯示中間那一組(第2組)的 section
當滑動到 第2組的最后一個 items 時, 再次滾動顯示第3組的第一個items
當在第3組的第一個items 繼續往后滾動時, 顯示第2組的第2個item , 然后保持在第2組中往后滾動, 直到最后一個items 重復上面的步驟.
無限滾動代碼實現.
//MARK: - selector event 下一頁
@objc private func nextPage(){
//print("下一頁")
// 獲取當前 inexPath
let currentIndexPath = self.collectionView?.indexPathsForVisibleItems.last!
// 獲取中間組 indexPath (所有的圖片都是最中間的那一組 為主)
let middleIndexPath = IndexPath(item: (currentIndexPath?.item)!, section: 1)
// 直接顯示中間那一組
collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false)
// 要動畫挪動的下一個 圖片
var nextItem = middleIndexPath.item + 1
var nextSection = middleIndexPath.section
if nextItem==imageUrls?.count{
// 當最后一張圖片時, 要回到第一個圖片顯示. 這里借用了第二組的第一個 item
nextItem = 0
nextSection += 1
}
let nextIndexPath = IndexPath(item: nextItem, section: nextSection)
//pageControl?.currentPage = nextItem
collectionView?.scrollToItem(at: nextIndexPath, at: .left, animated: true)
}
- 方法
collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false)
的理解
// 這句代碼, 要理解 animated 參數,
// 當 animated=true 時候, 有動畫效果.
// 當 animated=false , 沒有動畫效果, 直接就出現 要挪動到的 idnexPath
collectionView?.scrollToItem(at: middleIndexPath, at: .left, animated: false)
- 關于手動拖動滾動, 有兩種方式實現效果.
- 使用代理
scrollViewWillEndDragging
這里要做大量的判斷才行
- 使用代理
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let currentIndexPath = collectionView?.indexPathsForVisibleItems.last
// 防止 手動滑動圖片到 第一個或者最后一個 不循環滑動的問題
// 向左滑
if velocity.x > 0 {
if currentIndexPath?.section == (maxSections - 1) {
let nextIndexPath = IndexPath(item: (currentIndexPath?.item)!, section: 1)
collectionView?.scrollToItem(at: nextIndexPath, at: .left, animated: false)
}
}else{
// 向右滑
if currentIndexPath!.section == 0 {
let nextIndexPath = IndexPath(item: currentIndexPath!.item, section: 1)
collectionView?.scrollToItem(at: nextIndexPath, at: .right, animated: false)
}
}
}
- 2. 使用代理 `scrollViewDidEndDecelerating` 這里只有簡單的一句代碼就可以實現
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
collectionView?.scrollToItem(at: IndexPath(item: (pageControl?.currentPage)!, section: 1), at: .left, animated: false)
}
-
scrollViewDidEndDecelerating
和scrollViewDidEndScrollingAnimation
的區別-
scrollViewDidEndScrollingAnimation和scrollViewDidEndDecelerating的區別
scrollViewDidEndDecelerating
: 當手動拖動scrollView
動畫停止時, 會觸發
scrollViewDidEndScrollingAnimation
: 使用代碼實現scrollView
滾動動畫停止時 , 會觸發
-
scrollViewDidEndScrollingAnimation和scrollViewDidEndDecelerating的區別
- collectionView的內容向下偏移了一段位移
百度, 得知, 要在控制器中添加這句代碼
self.automaticallyAdjustsScrollViewInsets = NO;
automaticallyAdjustsScrollViewInsets 默認是 YES 這時候控制器會自動把 [scrollView , tableview, collectionView] 中的內容向自適應挪動一段距離, 這樣可以防止遮住 stateBar navigationBar toolBar SearchBar等. 一般我們都是自己管理collectionView的顯示范圍, 不需要自動調整
關于 swift 三方庫的使用
OC項目 中 在swift 文件中 使用 swift 三方庫
直接 import 三方庫
就可以使用-
OC 項目中 在 oc 文件中 使用 swift 三方庫
要在 oc 項目中 引入文件三方庫名-Swift.h
文件, 這個文件是系統自動生成的.
這樣就可以在 OC 文件中調用 swift 三方庫的方法了, 系統會自動把swift 方法映射為 oc 方法.
不過, 某些swift 特性不能轉化為 oc , 故 很多swift 方法不會映射為 oc 方法, 所以有一部分swfit方法 oc 文件不能使用
更多詳細介紹看這篇文章 Swift和Objective-C混編的注意啦
Snapkit
swift 中使用自動布局庫 Snapkit (跟oc 中的 masonry 用法相似)
參考文章 Swift編程(六):Snapkit的啟示錄
使用過程:
pod 集成Snapkit
: pod 'SnapKit', '~> 3.2.0'
在oc 自動布局庫 masonry 中, 子控件必須全部都加入到父視圖之后, 才對每一個子視圖進行布局
在 swift 'Snapkit' 中好像不需要, 加入父視圖后, 可以立即進行布局
```
pageControl!.snp.makeConstraints { (make) in
make.left.right.equalTo(0)
make.bottom.equalTo(-20)
make.height.equalTo(30)
}
```
Kingfisher
開始添加網絡圖片
輪播圖 , 有個本地默認圖片, 和網絡加載后的圖片
當網絡加載還沒有完成時, 顯示本地圖片, 當網絡加載結束后, 用網絡圖片代替本地圖片
swfit 中 網絡圖片框架
Kingfisher
竟然是喵神的作品,
開始學習Kingfisher
的用法, 先簡單的接觸, 會加載網絡圖片就好, 等手頭的項目結束后再去仔細讀源碼
學習步驟.
- pod 集成
Kingfisher
:pod 'Kingfisher', '~> 3.10.4'
網絡圖片素材:
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/11/pic_1502416479862.jpg
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/10/pic_1502331229612.jpg
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/07/pic_1502085582890.jpg
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/07/pic_1502085108072.jpg
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/08/04/pic_1501819284994.jpg
http://61.144.248.2:8085/carManager/html/ueditor/jsp/upload/info/2017/07/31/pic_1501466845618.jpg
這里只需要用到 下面的方法就好
cell.bannerImage?.kf.setImage(with: <#T##Resource?#>, placeholder: <#T##Image?#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> ()#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> ()#>)
這個方法里, 我們只需要傳入參數,
Resource
: URL 要緩存的網絡圖片
placeholder
: UIimage 站位圖片
options
: 操作類型 數組 [KingfisherOptionsInfoItem]
progressBlock(receivedSize, totalSize)
圖片下載過程回調
completionHandler(image,error,type,url)
圖片下載完成 回調
這個方法, 和 SDWebimage 的圖片緩存方法差不多.
- 自定義 初始化方法,
一直沒有走出 OC 的語言區域, 導致自定義初始化方法失敗.//失敗的自定義初始化方法: initWithArr(imageArr:[UIImage], titleArr:[String]){ } // 正確的自定義初始化方法 convenience init(imageArr:[UIImage], titleArr:[String]){ }
- 輪播圖 點擊回調事件, 打算用代理來寫 邏輯更清晰.
將點擊事件使用代理的方式傳遞出去.
注意: swift 中的協議前面需要加上 @objc(協議名字), 如下面的例子, 只有這樣才能在 oc 文件中使用該代理
@objc(BannerViewDelegate)
public protocol BannerViewDelegate:NSObjectProtocol{
全部封裝完畢, 當我們項目需要用到 輪播圖模塊時 ,只需要把文件引入, 在工程中添加下面的代碼就好.
BannerView *banner = [[BannerView alloc] initWithFrame:frame viewController:self imageArr:self.imageUrlArr placeHoldImage:placeImage titleArr:self.titleArr];
[self.view addSubview:banner];
- 遇到的其他問題
- 關于 閉包 閉包(Closures)
為什么要單獨封裝 一個輪播器出來呢.
封裝意味著 我的業務邏輯不必被實現細節所污染
把業務邏輯和功能實現細節分離開. 降低了程序的耦合性.
demo 暫時先不放出來了, 大家可以自己封裝一個玩一玩,
如果需要救急的話, 私信我, 給你扔demo
- 2018-08-31 demo 更新
https://gitee.com/iOS_binbin/MyUILibrary.git