我们使用UITableView实现了很多不同的用户界面,但是对于有些需求,比如横向滑动列表等等!它能发挥的作用还是有限的。后来,苹果在iOS 6中增加了一个类 — UICollectionView,用来弥补表视图的不足。UICollectionView和UITableView有很多相似之处,比如都有数据源和代理方法,以及需要注册cell以便重用。
UICollectionView的工作流程:
数据源方法,用来提供数据相关的内容
- numberOfSectionsInCollectionView:
- collectionView: numberOfItemsInSection:
- collectionView: cellForItemAtIndexPath:
- collectionView: viewForSupplementaryElementOfKind: atIndexPath: // 用于headerView和footerView
代理方法,负责用户交互,比如管理视图的高亮,选中,编辑
- collectionView:shouldDeselectItemAtIndexPath:
- collectionView:didSelectItemAtIndexPath:
- collectionView:didDeselectItemAtIndexPath:
- collectionView:shouldHighlightItemAtIndexPath:
- .....
接下来实现如下图的效果:
第一步,肯定是创建一个基于Single View Application模板的项目啦。打开Main.storyboard文件,选中里面的视图控制器并删掉,拖曳一个Collection View Controller进去,在Identity inspector修改好视图控制器的名称。这里命名为FTTViewController。
自定义单元
需要两个单元,一个用于包含单词的单元,一个用作分区标题的单元。首先创建第一个单元,继承于UICollectionViewCell。
#import <UIKit/UIKit.h>
@interface FTTContentCell : UICollectionViewCell
@property (strong, nonatomic) UILabel *label;
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) UILabel *lineLabel;
+ (CGSize)sizeForContentString:(NSString *)str; //根据字符串的长度来计算出单元的大小
@end
接着切换到FTTContentCell.m文件,重写initWithFrame:方法
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.label = [[UILabel alloc] initWithFrame:self.contentView.bounds];
self.label.opaque = NO;
self.label.backgroundColor = [UIColor colorWithRed:0.8
green:0.9
blue:1.0
alpha:1.0];
self.label.textColor = [UIColor blackColor];
self.label.textAlignment = NSTextAlignmentCenter;
[self.contentView addSubview:self.label];
self.lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.contentView.bounds.origin.y + self.label.frame.size.height, self.contentView.bounds.size.width , 1)];
self.lineLabel.backgroundColor = [UIColor redColor];
[self.contentView addSubview:self.lineLabel];
}
return self;
}
计算单元的合适尺寸
+ (CGSize)sizeForContentString:(NSString *)str {
CGSize maxSize = CGSizeMake(300, 1000);
NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineBreakMode:NSLineBreakByCharWrapping];
NSDictionary*attributes = @{NSFontAttributeName: [self defaultfont],
NSParagraphStyleAttributeName: style};
CGRect rect = [str boundingRectWithSize:maxSize options:opts attributes:attributes context:nil];
return rect.size;
}
接着,创建一个FTTHeaderCell文件,让它继承FTTContentCell,在FTTHeaderCell.m中做一下修改,覆盖掉initWithFrame:方法,改变单元的外观。
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.label.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.8 alpha:1.0];
self.label.textColor = [UIColor blackColor];
}
return self;
}
最后呢,选中FTTViewController.m文件,导入FTTHeaderCell.h和FTTContentCell.h。在viewDidLoad方法中定义好数据。
如前面所说,与UITableView很相似,UICollectionView同样需要基于一个标识符来注册需复用的单元类。
self.sections = @[
@{@"header": @"First", @"content": @"I believe that tomorrow will be a sunday! Do you believe me?"},
@{@"header": @"second", @"content": @"when everything would be fine."},
@{@"header": @"Third", @"content": @"That will be great"},
@{@"header": @"Fouth", @"content": @"How are you today?"},
];
[self.collectionView registerClass:[FTTContentCell class] forCellWithReuseIdentifier:@"CONTENT"];
self.collectionView.backgroundColor = [UIColor whiteColor];
UICollectionViewLayout *layout = self.collectionView.collectionViewLayout;
UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout *)layout;
[self.collectionView registerClass:[FTTHeaderCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HEADER"];
对字符串进行处理,将其分离出一个一个的单词,并存到一个数组中。
- (NSArray *)wordsInSection: (NSInteger) section {
NSString *content = self.sections[section][@"content"];
NSCharacterSet *space = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *words = [content componentsSeparatedByCharactersInSet:space];
return words;
}
实现数据源方法:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return [self.sections count];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
NSArray *words = [self wordsInSection:section];
return [words count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSArray * words = [self wordsInSection:indexPath.section];
FTTContentCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"CONTENT" forIndexPath:indexPath];
cell.text = words[indexPath.row];
return cell;
}
到这里,构建并运行应用,会发现单词的布局很混乱,此时,需要一个辅助类来处理下布局,这个类就是UICollectionViewFlowLayout啦,实现其中的一个委托方法,它用于得到分区中的单词,调用FTTContentCell类中的一个方法计算出单元的尺寸。
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSArray *words = [self wordsInSection:indexPath.section];
CGSize size = [FTTContentCell sizeForContentString:words[indexPath.row]];
return size;
}
为视图中的每个分区提供一个分区标题:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
if ([kind isEqual:UICollectionElementKindSectionHeader]) {
FTTHeaderCell *cell = [self.collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HEADER" forIndexPath:indexPath];
cell.text = self.sections[indexPath.section][@"header"];
return cell;
}
return nil;
}
现在,构建并运行,咦?标题怎么没有呢?!其实,标题没有出现是因为UICollectionViewFlowLayout不会为标题视图提供任何的显示空间,所以,需要对标题视图作明确的尺寸指定。在viewDidLoad方法中对属性headerReferenceSize做下设置就好啦。
flow.headerReferenceSize = CGSizeMake(100, 30);