前言
瀑布流布局是比较流行的一种网站页面和手机App布局,视觉表现为参差不齐的多栏布局,随着页面滚动条向下滚动,这种布局还会不断加载数据块并附加至当前尾部。最早采用此布局的网站是Pinterest,逐渐在国内流行开来,目前很多小清新网站和手机App基本都为此类风格。瀑布流对于图片的展现,是高效而具有吸引力的,它有如下优点
- 有效的降低了界面复杂度,节省了空间。
- 对触屏设备来说,交互方式更符合直觉,在移动应用的交互环境当中,通过向上滑动进行滚屏的操作已经成为最基本的用户习惯,而且所需要的操作精准程度远远低于点击链接或按钮。
- 有更高的参与度,以上两点所带来的交互便捷性可以使用户将注意力更多的集中在内容而不是操作上,从而让他们更乐于沉浸在探索与浏览当中。
下面我们说说瀑布流在iPhone手机上的实现过程。
UICollectionView
在iOS6以前,iOS的布局只有UITableView可以用,一些复杂的排版布局需要自己组装UITableView或者甚至搭配UIScrollView来实现,既麻烦而且一定程度上影响流畅度和性能。然而从iOS6开始,UICollectionView出现了,它是一种新的数据展示方式,简单来说可以把他理解成多列的UITableView(请一定注意这是UICollectionView的最最简单的形式)。如果你用过iBooks的话,可能你还对书架布局有一定印象:一个虚拟书架上放着你下载和购买的各类图书,整齐排列。其实这就是一个UICollectionView的表现形式,或者iPad中的原生时钟应用中的各个时钟,也是UICollectionView的最简单的一个布局。
主要接口
如果你用过UITableView,那么其实UICollectionView最简单的用法也差不多。
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
cell.label.frame = cell.bounds;
cell.label.text = [self.dataSource objectAtIndex:indexPath.row];
return cell;
}
UITableView则为
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyUITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"myCell"];
if (!cell) {
cell = [[MyUITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
}
cell.backgroundColor = [UIColor yellowColor];
cell.label.frame = cell.bounds;
cell.label.text = [self.dataSource objectAtIndex:indexPath.row];
return cell;
}
可以发现UICollectionView比UITableView简洁不少,但是需要在使用前注册
[_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
UICollectionView还提供了强大的Supplementary View和Decoration Views(本文不做阐述),Supplementary View可以理解为补充的View,业务中使用最广泛的是将其加到整个View的头部和尾部,类似于UITableView的headerView和footerView。同样它也需要使用前注册
//HintCell 继承 UICollectionReusableView
[_collectionView registerClass:[HintCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Hint"];
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
HintCell *HintView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Hint" forIndexPath:indexPath];
return HintView;
}
需要注意的