最近研究了UICollectionview。UICollectionview是ios6新增的一款UI控件。它是一個網格控制器。類似於UITableview控件。UICollectionView 繼承了UIScrollView,具有UIScrollView的功能。UIScrollView中封裝了UITableview cell的單元格控件。UICollectionview可以默認的進行對單元格的滑動。
我們可以通過代碼或者在故事版中創建UICollectionview。我習慣用故事版來創建UICollectionview。通過事件檢查器我們可以發現UICollectionview的佈局方式有兩種一種是Flow一種是CUstomer。如果選擇了Flow類型的話,就使用UIcollectionViewFlowLayout佈局對象。如果選擇Customer的話就會使用自定義的UICollectionViewLayout.
本文主要說的是Flow佈局模式
UIcollectionview採用的是流的佈局模式管理cell單元格。要麼縱向排列要麼橫向排列。其效果就是一個網格。
在檢查器中我們可以看到以下屬性
1.Scroll Direction
這個屬性主要是用於設置控件的滾動方向。支持Vertical和Horizontal兩個屬性值。選擇了custom的話,該屬性便不會出現。
2.Accessories
該屬性是否顯示UIcollectionview分區的頁眉或頁腳。
UIcollectionview同樣會採用Section來管理多個單元格。同樣使用NSIndexPath來封裝單元格的位置信息。此方式與UITableview相似。
使用UIcollectionview主要是實現兩個協議中的特定的方法。
我們要在。h文件中要使用者兩個協議
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
@property(strong,nonatomic)NSMutableArray * _contentArray;//我們這裏聲明一個存的變量名稱
end
在。m文件裏我們就要實現方法了。我主要是採用圖片形式來描述
<div> </div><div>-(void)setUpCollection{
NSArray * mainDishImages=[NSArray arrayWithObjects:"圖片名字" nil];
NSArray *drinkDessertImages=[NSArray arrayWithObjects:@“圖片名字”, nil];</div><div>//這裏主要用來表示不同的Section簡單的定義此方法在viewDidLoad裏調用。我習慣性在viewDidload方法中精簡代碼,使代碼分開顯示。
_imageArray=[NSArray arrayWithObjects:mainDishImages,drinkDessertImages, nil];
self.mycollectionview.delegate=self;
self.mycollectionview.dataSource=self;
</div><div> }</div><div> </div>
//這裏表示有多少items
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return[[_imageArray objectAtIndex:section]count];
}
//這裏主要表示有多少section
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return [_imageArray count]; }
頁眉我們可以在故事版中設置模板的這裏我們設置了一個UILable
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{ if (kind==UICollectionElementKindSectionHeader) { UICollectionReusableView* headViews=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; NSString * title=[[NSString alloc]initWithFormat:@"本週"]; headViews.title.text=title; } return headViews; }
這樣我們就做好了