UICollectionView

iOS CollectionView的出現是一大福利,不再用用TableView來定義複雜的多欄表格了,用法與Table相似,只是Cell必須本身添加,無默認模式web

因爲CollectionView沒有默認的Cell佈局,因此通常仍是自定義方便又快捷佈局

1、自定義Cellspa

一、新建類CollectionCell繼承自UICollectionViewCell.net

二、新建Xib,命名爲CollectionCell.xib代理

a.選中CollectionCell.xib刪掉默認的View,從控件中拖一個Collection View Cell(圖3)到畫布中,設置大小爲95*116code

 

b.選中剛剛添加的Cell,更改類名爲CollectionCell,如圖4orm

c.在CollectionCell.xib的CollectionCell中添加一個ImageView和一個Label(圖5)繼承

d.建立映射, 圖6,圖7事件

e.選中CollectionCell.m , 重寫init方法圖片

01 - (id)initWithFrame:(CGRect)frame
02 {
03     self = [super initWithFrame:frame];
04     if (self) {
05         // 在此添加
06          
07         // 初始化時加載collectionCell.xib文件
08         NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options: nil];
09          
10         // 若是路徑不存在,return nil
11         if(arrayOfViews.count < 1){return nil;}
12          
13         // 若是xib中view不屬於UICollectionViewCell類,return nil
14         if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]){
15             return nil;
16         }
17          
18         // 加載nib
19         self = [arrayOfViews objectAtIndex:0];
20     }
21     return self;
22 }

2、定義UICollectionView;

一、拖動一個Collection View到指定ViewController的View上

二、連線dataSource和delegate,並建立映射,命名爲CollectionView

三、選中CollectionView的標尺,將Cell Size的Width和Height改爲與自定義的Cell同樣的95*116,圖8

    

四、選中CollectionView的屬性,能夠修改其屬性,好比是垂直滑動,仍是水平滑動,選擇Vertical或Horizontal

五、在ViewDidLoad方法中聲明Cell的類,在ViewDidLoad方法中添加,此句不聲明,將沒法加載,程序崩潰

1 // KCellID爲宏定義 @"CollectionCell"
2 [self.collection registerClass:[CollectionCell class] forCellWithReuseIdentifier:KCellID];

六、在ViewController.h中聲明代理

1 @interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>

七、在.m文件中實現代理方法

01 -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
02 {
03     // 每一個Section的item個數
04     return 12;
05 }
06 -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
07 {
08      
09     CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:KCellID forIndexPath:indexPath];
10      
11     // 圖片的名稱
12     NSString *imageToLoad = [NSString stringWithFormat:@"%d.JPG", indexPath.row];
13     
14     // 設置label文字
15     cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.row,(long)indexPath.section];
16      
17     // 設置imageView的圖片
18     cell.imageView.image = [UIImage imageNamed:imageToLoad];
19      
20     return cell;
21  
22 }

效果如圖10

點擊某項後跳轉事件與UITableView相似,實現代理方法

1 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

便可,不贅述

相關文章
相關標籤/搜索