![](/img/trans.png)
[英]How to add header and footer view of UICollectionView in Swift
[英]How to add pagination in UICollectionView in swift?
我有一個顯示項目的 UICollection 視圖。 現在我想在 UICollectionView 上添加分頁。 我不想為此功能使用任何第三方。 請讓我知道如何實現這一目標!
我有四個一個例子http://slicode.com/bottom-refresh-control-uicollectionview/
但在此我必須向上拖動滾動視圖幾秒鍾才能使其工作。
簡單的方法來做到這一點
var page: Int = 0
var isPageRefreshing:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
YourApi(page1: 0)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if(self.mycollectionview.contentOffset.y >= (self.mycollectionview.contentSize.height - self.mycollectionview.bounds.size.height)) {
if !isPageRefreshing {
isPageRefreshing = true
print(page)
page = page + 1
YourApi(page1: page)
}
}
}
在您的 api 方法中
func YourApi(page1: Int) {
let mypage = String(page1)
let request: String = String.init(format:"apiName/%@", mypage)
print(request)
}
而已。
如果要添加底部刷新控件,則必須使用下面的幫助程序類。
https://github.com/vlasov/CCBottomRefreshControl/tree/master/Classes
下載Objective-C中的這2個文件。 您必須在橋接頭中導入此文件
#import "UIScrollView+BottomRefreshControl.h"
像這樣添加刷新控件。
let refreshControl = UIRefreshControl.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
refreshControl.triggerVerticalOffset = 50.0
refreshControl.addTarget(self, action: #selector(paginateMore), for: .valueChanged)
collectionView.bottomRefreshControl = refreshControl
這個幫助類為你提供了新的bottomRefreshControl
屬性,它可以幫助你在底部添加刷新控件。
我在我的一個應用程序中添加了加載更多功能,所以讓我給你代碼
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
referenceSizeForFooterInSection section: Int) -> CGSize {
if arrData.count > 0 && isLastPageReached == false
{
return CGSize(width:(collectionView.frame.size.width), height: 100.0)
}
return CGSize.zero
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionFooter {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)
let loading = UIActivityIndicatorView()
loading.activityIndicatorViewStyle = .gray
loading.translatesAutoresizingMaskIntoConstraints = false
loading.tintColor = UIColor.gray
loading.tag = -123456
view.addSubview(loading)
view.addConstraint(NSLayoutConstraint(item: loading, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
vew.addConstraint(NSLayoutConstraint(item: loading, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))
return view
}
return UICollectionReusableView()
}
func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
if elementKind == UICollectionElementKindSectionFooter {
if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
if arrData.count > 0 && isLastPageReached == false
{
loadingView.startAnimating()
self.loadMore()
}
else
{
self.isLoadMore = false
}
}
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
if elementKind == UICollectionElementKindSectionFooter{
if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
loadingView.stopAnimating()
loadingView.removeFromSuperview()
self.isLoadMore = false
}
}
}
請試試這個它對我有用。
步驟1:
聲明一個全局變量:
var totalCount : NSInteger?
var isGetResponse : Bool = true
var activityIndiator : UIActivityIndicatorView?
設置 viewDidLoad:
activityIndiator = UIActivityIndicatorView(frame: CGRect(x: self.view.frame.midX - 15, y: self.view.frame.height - 140, width: 30, height: 30))
activityIndiator?.activityIndicatorViewStyle = .white
activityIndiator?.color = UIColor.black
activityIndiator?.hidesWhenStopped = true
activityIndiator?.backgroundColor = COLOR.COLOR_TABLEVIEW_BACKGROUND
activityIndiator?.layer.cornerRadius = 15
self.view.addSubview(activityIndiator!)
self.view.bringSubview(toFront: activityIndiator!)
第二步:在api調用方法中設置值:
self.totalCount = array.count
self.isGetResponse = true
第 3 步:編寫此代碼:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isGetResponse {
if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height)
{
if totalArrayCount! > self.arrProductListing.count{
isGetResponse = false
activityIndiator?.startAnimating()
self.view.bringSubview(toFront: activityIndiator!)
pageIndex = pageIndex + 1
print(pageIndex)
self.getProductListing(withPageCount: pageIndex)
}
}
//LOAD MORE
// you can also add a isLoading bool value for better dealing :D
}
}
在服務調用中,您可以發送頁面索引並從服務器端發回響應。
謝謝你。
CollectionView 委托方法:在 CollectionView 上加載更多關於滾動需求的數據。
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == numberofitem.count - 1 { //numberofitem count
updateNextSet()
}
}
func updateNextSet(){
print("On Completetion")
//requests another set of data (20 more items) from the server.
}
以下兩個函數負責分頁。 正如你在下面看到的。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if current_page < total_page && indexPath.row == cars.count - 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "loading_cell", for: indexPath) as! PaginationCollectionViewCell
cell.actIndicator.startAnimating()
return cell
}else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PaginationCollectionViewCell
cell.lbTitle.text = cars[indexPath.row].company_name
cell.lbDescription.text = cars[indexPath.row].engine_power
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if current_page < total_page && indexPath.row == cars.count - 1 {
current_page = current_page + 1
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
self.fetchData(page: self.current_page)
}
}
}
我在進行分頁時使用了該代碼。 重點是; 在集合視圖加載時捕獲加載的單元格索引,並使用數字控制它的 mod,並使用 api 中的頁面大小字段單獨獲取數據(如果有)。 您可以決定哪個數字將小於此計算,並且您將控制它。
例如,您獲取了 5 個數據並加載了它,如果此狀態正常,您將獲取其他 5 個。這是示例代碼。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let vc = self.parentViewController as? SellController {
if vc.dontFetch == false {
DispatchQueue.main.async {
if self.salesData.count > 3 {
if indexPath.row != 1 {
if indexPath.row % 3 == 1 {
print("indexpath: \(indexPath.row)")
vc.pagination += 1
vc.reload()
}
}
}
}
}
}
}
在這段代碼中,我控制 indexpath.row % 3 == 1 與否。 它可能有點復雜,所以如果你願意,我可以分享一個代碼塊。 祝你好運:)
-- itemList - 你的數據數組。
-- pageCount - 用於跟蹤頁數的變量。
-- totalCount - 數據總數
--- 每次調用 API 時將數據附加到itemList 。
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == itemList.count - 1 && itemList.count < totalCount{
pageCount += 1
// Call API here
}
}
willDisplay cell
方法中的代碼調用 load more 函數,而您的滾動距離末端 5 個單元格。 獲取數據時在集合視圖頁腳中顯示加載程序。 加載完成后隱藏頁腳。
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let currentPage = collectionView.contentOffset.y / collectionView.frame.size.width;
if (aryDataSource.count >= yourAPIResponsebatchCount && aryDataSource.count - indexPath.row == 5 && currentPage >= currentPage && isDataLoading) {
currentPage++;
self.fetchMoreData()
}
else { }
}
我瀏覽了這個線程中的所有答案,所有答案似乎都實現起來有點復雜。 我的情況需要一個集合視圖分頁,其中頁面的寬度與屏幕寬度相同,對於這種特殊情況,解決方案是:
collectionView.isPagingEnabled = true
我不是 100% 確定這是否適用於頁面寬度與屏幕寬度不同的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.