Uicollectionview is a new way of presenting data that can be simply interpreted as a multi-column uitableview. If you have used ibooks, you may also have a certain impression of the Bookshelf layout, a virtual bookshelf with all kinds of books you download and buy, neatly arranged. This is actually a uicollectionview representation, or the clock in the native clock application in the ipad's iOS6, and the simplest layout of the Uicollectionview.
Collection View Uicollectionview Introduction
The collection view Uicollectionview is similar to the table View UITableView, which displays the contents of the cell collection according to the Layout property settings. The Uicollectionviewdatasource class provides data to the collection view as a data source for the collection view. The collection view relies on the methods defined in the delegate (Delegate) to respond to user interaction.
The three elements that make up the collection View are: cell (Uicollectionviewcell), supplemental view (Supplementary views-display additional metadata information), and decorative view (decoration views).
No matter how the layout of a uicollectionview changes, these three parts are present.
Why use a collection view?
- Can be highly customized display of content;
- Best practices for managing data;
- Can efficiently process large amounts of data;
Collection View Cell Uicollectionviewcell
Similar to Table view cell UITableViewCell, it has a Indexpath property that defines which row and node it belongs to, and other properties that define the visual display. Somewhat unlike UITableViewCell, Uicollectionviewcell does not have any predefined types, and we have to set the cells manually.
Collection View Layout uicollectionviewlayout
This class controls how the cells are laid out, such as positioning, transparency, and hierarchy (Z-index), and so on. Uicollectionviewflowlayout is a pre-defined subclass of uicollectionviewlayout that sets the flow layout to be displayed by row. However, we can further reload its properties or develop subclasses to customize.
Collection View Data source Uicollectionviewdatasource
Like Uitableviewdatasource, Uicollectionviewdatasource is responsible for providing cells to the collection view. Defined by the Uicollectionviewdatasource protocol, the Protocol provides a number of necessary methods, as well as a large number of optional methods.
Collection View Delegate Uicollectionviewdelegate
Like the table view delegate uitableviewdelegate, it handles user interaction and is defined by the Uicollectionviewdelegate protocol.
Create a simple collection view application
Let's start by creating a simple application that applies a collection view, and see how it works.
Using Xcode's single View application template, create a project with a project name of Simplecollectionview and a class prefix of simple. For this project, we do not select Use storyboards, but select the use Automatic Reference counting check box.
In order to create a collection view, you need to have the class conform to the associated protocol for the collection view. Open the SimpleViewController.h file and add the Uicollectionviewdatasource and Uicollectionviewdelegate protocols.
#import <UIKit/UIKit.h>
@interface SimpleViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate>
@end
Then open the Simpleviewcontroller.xib file, drag the Uicollectionview object from the object library into the view, and let the collection view fill the entire view.
Then establish the Uicollectionview object to the output port in the view controller as follows:
@property (Strong, nonatomic) Iboutlet Uicollectionview *collectionview;
Switch back to the Simpleviewcontroller.xib file, control-click the Uicollectionview object in the view, drag to the file's owner icon, and select DataSource from the pop-up menu. Repeat the same operation and connect to the delegate outlet.
This completes the connection of the Uicollectionview object to the DataSource and delegate outputs. Next, we need to prepare the data for Uicollectionview.
to make the application simpler, we add some private properties to the SIMPLEVIEWCONTROLLER.M implementation file's additional directory (continuation Category) as follows:
#import "SimpleViewController.h"
@interface simpleviewcontroller ()
@property (nonatomic , strong) Nsarray *dataarray;
@end
The DataArray array will hold the data needed for the Uicollectionview. We initialize 2 arrays in the Viewdidload method, 2 sections respectively, each comprising 50 nsstring data items.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray *firstSection = [[NSMutableArray alloc] init];
NSMutableArray *secondSection = [[NSMutableArray alloc] init];
for (int i=0; i<50; i++){
[firstSection addObject:[NSString stringWithFormat:@"单元格 %d", i]];
[secondSection addObject:[NSString stringWithFormat:@"数据项 %d", i]];
}
self.dataArray = [[NSArray alloc] initWithObjects:firstSection, secondSection, nil];
}
After creating the data, we need to tell the collection view a few parts (section), which means we need to implement the Numberofsectionsincollectionview: method.
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return [self.dataArray count];
}
After the collection view knows that there are several parts, we also need to tell the collection view: The data items that each section contains. Therefore, we need to implement the Collectionview:numberofitemsinsection: method.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSMutableArray *sectionArray = [self.dataArray objectAtIndex:section];
return [sectionArray count];
}
Now, the collection view already knows several parts, and each part of the data item. Next, we create the cells that are used for the display.
Create a collection view cell Uicollectionviewcell
Table View UITableView provides some standard cell layouts, but for uicollectionview, we need to create our own cells. As simple as creating cells in a table view, we can create cells in a standalone xib file, or a Uicollectionviewcell subclass. Below, we will show both methods separately.
Create a collection view cell using the Xib file
To create a new view file, select Files > New > File ... menu item, from the iOS user interface node, select the View template, and the new file is named Nibcell.
Xcode will automatically open this file, we delete the default view, and then drag the collection view Cell object into the canvas from the object library.
Select the above cell view in the Size Inspector panel window and resize to 100x100.
Then in the Attributes Inspector panel window, set the background color for your favorite color. Here, we set the background color to yellow.
We add a label label to the cell. Select the tab, and in the Attributes Inspector panel window, set its Tag property to 10. We use this property value in the following code.
Once the Xib file is created, we now need to associate it with the collection view. At the same time, we also apply the Uicollectionviewlayout layout to the collection view. Back in the View Controller implementation code file, update the Viewdidload method and add the following code:
UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"simpleCell"];
The preceding code gets the Xib file created earlier and registers it in the collection view, setting the reusable identifier as Simplecell, which can be used to out-queue and instantiate a new cell that is available for use.
A collection view is not useful if it has no layout. Therefore, we need to create a layout. Add the following code to the bottom of the Viewdidload method.
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(100, 100)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
flowLayout.sectionInset = UIEdgeInsetsMake(0, 2, 0, 0);
[self.collectionView setCollectionViewLayout:flowLayout];
The code above first creates an instance of the Uicollectionviewflowlayout object that is the available flow layout built into the iOS SDK. This object has a lot of properties to set, here we set 3 properties: (1) The size of item, the same size as the Uicollectionviewcell we created earlier, (2) scrolling method; (3) sets the interval between sections of the collection view. Finally, we add a well-configured layout to the collection view.
Now, we're ready to implement the method, returning the cells that are needed for the collection view, which is Collectionview:cellforitematindexpath: methods, and Tableview:cellforrowatindexpath : The method is very similar. In the View Controller implementation file, add the following method code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
NSString *cellData = [data objectAtIndex:indexPath.row];
static NSString *cellIdentifier = @"simpleCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UILabel *titleLabel = (UILabel *)[cell viewWithTag:10];
titleLabel.text = cellData;
return cell;
}
The code above first gets the data source of the specified section from the DataArray data source, and gets the specified row data from the cell string from the data array. Next, create a cellidentifier reference that requires the collection view to take out a reusable cell with the cellidentifier identifier. If a reusable cell exists in the cache of the collection view, it will be returned to us, otherwise the collection view will create a new cell object for us behind the scenes. We don't have to know the process behind the scenes, just understand Dequeuereusablecellwithreuseidentifier:forindexpath: The method always returns a Uicollectionviewcell object.
We previously added a Uilabel tag to the Uicollectionviewcell and set the Tag property to 10. This means that we can examine the cell and get a reference to the label and convert it to the Uilabel variable so that the Uilabel property can be accessed further.
Once the Uilabel property can be accessed, we set its Text property value and eventually return the cell, which is displayed in the collection view.
Running the Simplecollectionview application
Now that the code is written, we run the Simplecollectionview application and the effect should look like this.
As shown, 2 section data is displayed in the collection view.
To create a collection class cell using the Xib file