iOS UI-集合視圖(UICollectionView)


BowenCollectionViewCell.xib

  1 #import <UIKit/UIKit.h>
  2 
  3 @interface BowenCollectionViewCell : UICollectionViewCell
  4 
  5 @property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
  6 
  7 @property (weak, nonatomic) IBOutlet UILabel *lalName;
  8 @property (weak, nonatomic) IBOutlet UILabel *lblPosition;
  9 @property (weak, nonatomic) IBOutlet UIButton *btnManInfo;
 10 @property (weak, nonatomic) IBOutlet UITextView *textViewStory;
 11 
 12 @end
 13 
 14 #import "BowenCollectionViewCell.h"
 15 
 16 @implementation BowenCollectionViewCell
 17 
 18 - (void)awakeFromNib {
 19     // Initialization code
 20 }
 21 
 22 @end
 23 
 24 #import "ViewController.h"
 25 #import "BowenCollectionViewCell.h"
 26 
 27 /*
 28  集合視圖:UICollertionView
 29  三個協議、兩個代理、四或五個方法
 30  
 31  UICollectionViewDataSource          加載數據
 32  UICollectionViewDelegate            執行代理
 33  UICollectionViewDelegateFlowLayout  布局
 34 
 35  使用步驟
 36  0.創建單元格ID
 37  1.創建布局(橫向布局、縱向布局)
 38  2.創建集合視圖,設置代理
 39  3.注冊單元格
 40  4.加載視圖
 41  */
 42 
 43 @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
 44 
 45 @property (nonatomic, strong) UICollectionView *collectionView;
 46 @property (nonatomic, strong) NSIndexPath *indexPath;
 47 
 48 @end
 49 
 50 @implementation ViewController
 51 
 52 static NSString *cellIdentyfier = @"cellIndentyfier";
 53 
 54 - (void)viewDidLoad {
 55     [super viewDidLoad];
 56     
 57 //    1.創建布局(橫向布局、縱向布局)
 58     UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
 59     [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
 60     
 61 //    2.創建集合視圖,設置代理
 62     self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
 63     self.collectionView.dataSource =self;
 64     self.collectionView.delegate = self;
 65 //    3.注冊單元格(item)
 66     [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentyfier];
 67 //    4.加載視圖
 68     [self.view addSubview:self.collectionView];
 69 //      加載nib文件
 70     [self.collectionView registerNib:[UINib nibWithNibName:@"BowenCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:cellIdentyfier];
 71     
 72     
 73 }
 74 
 75 #pragma mark - 數據源
 76 // 加載組數
 77 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
 78 {
 79     return 2;
 80     
 81 }
 82 // item的個數
 83 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
 84 {
 85     return 2;
 86 }
 87 // item中的單元格加載數據的方法
 88 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
 89 {
 90     //集合視圖的單元格本身就是一個View,什么自帶控件都沒有
 91     //如果想使用集合視圖的item
 92     //1.直接往上面添加控件(不推薦) 官方規定:這個加載方法只能加載數據
 93     //2.自定義item使用
 94     BowenCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentyfier forIndexPath:indexPath];
 95     cell.contentView.backgroundColor = [UIColor whiteColor];
 96     
 97     //每個button都是不一樣的
 98     cell.btnManInfo.tag = indexPath.section*100 + indexPath.row;
 99     [cell.btnManInfo addTarget:self action:@selector(btnManInfoClick:) forControlEvents:UIControlEventTouchUpInside];
100 
101     return cell;
102 }
103 // 按鈕關聯方法
104 - (void)btnManInfoClick:(id)sender
105 {
106     UIButton *tempBtn = (UIButton*)sender;
107     NSInteger section = tempBtn.tag/100;
108     NSInteger row = tempBtn.tag%100;
109     switch (section) {
110         case 0:
111             if (row ==0) {
112                 NSLog(@"第0分組第0元素");
113             }
114             else{
115                 NSLog(@"第0分組第1元素");
116             }
117             break;
118         case 1:
119             if (row ==0) {
120                 NSLog(@"第1分組第0元素");
121             }
122             else{
123                 NSLog(@"第1分組第1元素");
124             }
125             break;
126         default:
127             break;
128     }
129 }
130 
131 #pragma mark - 代理方法
132 // 監聽行被選中執行的代理方法
133 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
134 {
135     NSLog(@"%@",indexPath);
136 }
137 
138 #pragma mark - 布局
139 // item的尺寸
140 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
141 {
142     return CGSizeMake(150, 150);
143     
144 }
145 // 每組的Header尺寸
146 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
147 {
148     return CGSizeMake(25, 25);
149     
150 }
151 
152 #pragma mark - 狀態欄
153 // 隱藏狀態欄
154 - (BOOL)prefersStatusBarHidden
155 {
156     return YES;
157 }
158 
159 - (void)didReceiveMemoryWarning {
160     [super didReceiveMemoryWarning];
161     // Dispose of any resources that can be recreated.
162 }
163 
164 @end

 一、UICollectionViewController的使用

1.注冊cell(告訴collectionView將來創建怎樣的cell)

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"product"];

 

2.從緩存池中取出cell

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"product" forIndexPath:indexPath]; 

    return cell;

}

 

3.重寫init方法,創建布局參數

- (id)init

{

    // 1.流水布局

      UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    // 2.每個cell的尺寸

      layout.itemSize = CGSizeMake(100, 100);

    return [super initWithCollectionViewLayout:layout];

}

 

二、UICollectionViewFlowLayout

UICollectionViewFlowLayout稱為”流水布局”, 用來約束cell的顯示
 
常見屬性
 
Cell的尺寸

@property (nonatomic) CGSize itemSize;

 

cell之間的水平間距

@property (nonatomic) CGFloat minimumInteritemSpacing;

 

cell之間的垂直間距

@property (nonatomic) CGFloat minimumLineSpacing;

 

四周的內邊距

@property (nonatomic) UIEdgeInsets sectionInset;

 

三、UICollectionView常用數據源方法

1.調用數據源的下面方法得知一共有多少組數據

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;

 

2.調用數據源的下面方法得知每一組有多少項數據

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;

 

3.調用數據源的下面方法得知每一項顯示什么內容

- (UICollectionViewCell *)collectionView:(UICollectionView *) collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

 

UICollectionView的數據源必須實現第二個方法和第三個方法,第一個方法不實現默認就是1組

 
四、 UICollectionView的常見屬性
1.布局對象

@property (nonatomic, strong) UICollectionViewLayout *collectionViewLayout;

 

2.背景視圖,會自動填充整個UICollectionView

@property (nonatomic, strong) UIView *backgroundView;

 

3.是否允許選中cell 默認允許選中

@property (nonatomic) BOOL allowsSelection;

 

4.是否可以多選 默認只是單選

@property (nonatomic) BOOL allowsMultipleSelection;

 

五、 UICollectionViewFlowLayout常用屬性

1.cell之間的最小行間距                                               
 @property (nonatomic) CGFloat minimumLineSpacing;
 
2.cell之間的最小列間距                                                                                                             
@property (nonatomic) CGFloat minimumInteritemSpacing;
3.cell的尺寸                                                                                                                                             
@property (nonatomic) CGSize itemSize;
 
4.cell的預估尺寸                                                                                                                         
@property (nonatomic) CGSize estimatedItemSize;
 
5.UICollectionView的滾動方向,默認是垂直滾動                                                                
 @property (nonatomic) UICollectionViewScrollDirection scrollDirection;
 
6.HeaderView的尺寸                                                
@property (nonatomic) CGSize headerReferenceSize;
 
7.FooterView的尺寸                                                       
@property (nonatomic) CGSize footerReferenceSize;
 
8.分區的四邊距                                                                                                                                             
@property (nonatomic) UIEdgeInsets sectionInset;
 
9.設置是否當元素超出屏幕之后固定頁眉視圖位置,默認NO                    
@property (nonatomic) BOOL sectionHeadersPinToVisibleBounds;
 
10.設置是否當元素超出屏幕之后固定頁腳視圖位置,默認NO                               
@property (nonatomic) BOOL sectionFootersPinToVisibleBounds
 
六、 自定義布局的常用方法
1.UICollectionView將要顯示時准備布局,每當布局更新時,調用該方法做布局前的准備                                                                    
- (void)prepareLayout;
 
2.創建指定索引的cell的布局屬性                                             
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPat;
 
3.返回UICollectionView內所有的控件的布局屬性                                
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
 
4.自定義布局時一定要實現此方法來返回UICollectionView的contentSize,內容尺寸,UICollectionView的滾動范圍                                            - (CGSize)collectionViewContentSize;

 

七、注冊cell的三種方式:

1> 用nib(xib)來注冊cell,表示cell如何去創建, 在注冊同時必須給cell設置重用標識

2> 用類(純代碼)來注冊cell,表示cell用代碼來創建,在注冊同時必須cell設置重用標識

3> 在storyboard中給cell,設置重用標識時會同時注冊cell

 

1純代碼實現

 常見錯誤

 錯誤1> ICollectionView must be initialized with a non-nil layout parameter

 實例化(創建)UICollectionView的同時必須指定一個非空的layout

 用UICollectionViewLayout這個類直接創建出來的布局對應就是一個空的布局,里面什么也沒有

 一般情況用UICollectionViewFlowLayout(流水布局,它創建出來有默認的itemSize,和行間距等等)

 

錯誤警告

 negative or zero item sizes are not supported in the flow layout

 UICollectionViewFlowLayout 不支持負得或為0尺寸cell

  當itemSize等於 CGSizeZero 數據源方法返回每一個cell的方法不會執行,說明只有cell有尺寸時才能返回cell

 layout.itemSize = CGSizeZero;

 

用class來注冊 cell(告訴collectionView中的cell如何創建),並給cell添加重用標識

 [collectionView registerClass:[CZAppCell class] forCellWithReuseIdentifier:ID];

   

2.用xib實現

// 加載xib

UINib *nib = [UINib nibWithNibName:@"CZAppCell" bundle:nil];

// 通過xib來注冊,告訴collectionView如何去創建cell,並指定重用標識

[self.collectionView registerNib:nib forCellWithReuseIdentifier:ID];

 

// 實例化xib

CZAppCell *cell = [[nib instantiateWithOwner:nil options:nil] lastObject];

// 根據xib中的cell的尺寸來設置布局屬性中cell的尺寸

self.flowLayout.itemSize = cell.bounds.size;

 

3.用storyboard實現

給storyboard的cell會只需添加重用標識即可自動注冊

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM