The uicollectionview class is almost identical to the uitableview Class. They share many of the same methods and functions. And if the methods / functions are different, most of the time it's just a matter of swapping out "row" for "cell" and vice versa. However there are a few methods that don't exist on UICollectionView that do on UITableView. First though, I'll explain how to setup a UICollectionView:
- Begin by adding your UICollectionView to a current ViewController, or creating a new UICollectionViewController. The steps aren't that much different for the view and controller.
If you're using the View and not the ViewController, make sure that the Delegate and DataSource of the CollectionView is the view controller it's on. Also make sure to add the Delegate and DataSource to your header file: <UICollectionViewDataSource, UICollectionViewDelegate>
Next, make sure to include these three methods in your view controller's class:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
These are the only required methods. The first tells the collection view the number of sections it should have. This should return an integer value. The second method gets the number of cells in each section. Again, this should return an integer value. The last method populates each cell using the data given (usually from an NSArray). This last method should return a CollectionViewCell. If you set breakpoints on this method, you'll notice that it is called once for every cell defined in the numberOfItemsInSection
method.
UICollectionViews provide advanced animation methods and allow cells to be deselected and selected (similar to apps like Pages when in 'Edit' mode). However, to my knowledge, UICollectionViews do not provide features such as "swipe to delete" or and kind of disclosure indicator.
UICollectionViews also allow you to create custom cells using xib (AKA nib) files, this allows for some very advanced-looking and unique interfaces without lots of complicated code.
Sadly, UICollectionView is only supported in iOS 6 and up. There are a few projects available such as PSTCollectionView which adds support for CollectionViews in iOS 4.3+, but I haven't figured out how to use them. In my case, when the view loads I just check if the UICollectionView Class is available and if it isn't then I load a Table instead.
Here is a link to Apple's official documentation on Collection Views. You might also want to check out this tutorial.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…