美文网首页
UICollectionView-Part2

UICollectionView-Part2

作者: oopp | 来源:发表于2015-09-07 18:47 被阅读253次

接着上一篇文章,来做一个简单的排版试试看,demo下载地址

想要实现的效果

有不少的App实现了这种类似于关键字排列的的效果,如图:


文字排版

对于这种排版的规则是什么呢?在不考虑文字换行,并且文字的长度超过container的长度的情况下,那么规则就是文字横向排列:如果该行的剩余长度大于文字的长度,那么就排列上去;如果该行的剩余长度小于文字长度,那么就换行.

咱们来撸码

创建一个工程balabala...
然后创建一个UICollectionView

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 320) / 2, 64, 320, 500) collectionViewLayout:layout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:collectionView];

没有什么奇怪的东西,因为是demo,所以直接使用了frame.当然auto layout更好啦~=.=

但是有一个小问题,这个初始化collection view的layout是什么东东呢?呃是咱们自己定义的layout所以在初始化collection view之前,还有这样一段代码

CustomLayout *layout = [[CustomLayout alloc] init];
layout.delegate = self;

暂时放下layout,我们写点很熟悉的代码.

初始化测试数据:

- (void)setupData {
    self.ds = [@[] mutableCopy];
    [self.ds addObjectsFromArray:@[@"aaa",@"bbbbbb",@"ccc",@"dddddddddd",@"eeee",@"fffffffffff",@"gggggggggggggg",@"hhhhhhhhhhh",@"iiiiii",@"jjj",@"kkkkkkkkkkk",@"llllllllll",@"mmmmmmmmm",@"nnn",@"o",@"ppppppp",@"qqqqqq",@"rrrrrrrrrrrrrrrrr",@"ssssssssss",@"tttt",@"uuuuuuuu",@"vvv",@"wwwwww",@"xxx",@"yyyyyyyyyy",@"zzzzzzzzzzzzzzzz"]];
}

几个不可缺少的代理方法:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.ds count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CellIdentifier" forIndexPath:indexPath];
    cell.textLabel.text = self.ds[indexPath.row];
    cell.clipsToBounds = YES;
    cell.layer.borderColor = [UIColor whiteColor].CGColor;
    cell.layer.borderWidth = 1;
    cell.layer.cornerRadius = 5;
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView widthForTextAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = self.ds[indexPath.row];
    CGRect frame = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, kLineHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    return ceil(frame.size.width);
}

Cell是很简单的,里面就包含了一个UILabel,用于显示文字.

CustomLayout

排版的关键在于这个layout,首先定义了几个常量:

#define kLeftMargin (5)
#define kLineSpace  (10)
#define kLineHeight (17)

分别表示cell之间的水平间隔,每一个cell的高度,cell之间的垂直间隔.

也定义了一个delegate,用于获取每一个cell的宽度:根据文字来计算宽度:

@protocol CustomLayoutDelegate <NSObject>

- (CGFloat)collectionView:(UICollectionView *)collectionView widthForTextAtIndexPath:(NSIndexPath *)indexPath;

@end

准备工作做好了以后,我们开始着手核心的layout计算:

- (void)prepareLayout {
    if (!self.cache) {
        self.cache = [@[] mutableCopy];
        NSInteger totalCount = [self.collectionView numberOfItemsInSection:0];
        CGFloat lineWidth = self.collectionView.bounds.size.width;
        leftWidthInLine = lineWidth;
        for (NSInteger i = 0; i < totalCount;i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            CGFloat width = [self.delegate collectionView:self.collectionView widthForTextAtIndexPath:indexPath];
            BOOL anotherLine = YES;
            if (leftWidthInLine - width - kLeftMargin > 0) {
                anotherLine = NO;
            }
            else {
                lines++;
                leftWidthInLine = lineWidth;
            }
            CGRect frame = CGRectMake(lineWidth - leftWidthInLine, (kLineHeight + kLineSpace) * (lines - 1), width, kLineHeight);
            leftWidthInLine -= (width + kLeftMargin);
            UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            attribute.frame = frame;
            [self.cache addObject:attribute];
        }
    }
}

我们通过一个属性lines来知道一共有多少行,所以它初始化应该为1.
我们需要知道一共有多少个数据,所以直接通过collection view获取到.
我们对每一个数据,都需要对比文字长度和这一行的剩余长度,所以有一个leftWidthInLine变量来保存每一行的剩余长度.

循环遍历所有的数据,通过CustomLayoutDelegate可以获取到每一个数据(文字)的长度.
如果leftWidthInLine大于文字长度,说明这一行能够容下,不需要换行.那么这行的frame为:

  • x:collection view的宽度减去leftWidthInLine
  • y:(lines(总行数) - 1) * (每一行的高度+每一行的垂直间隔)
  • w:代理获取到的文字长度
  • h:已经定义好的每一行的高度

如果leftWidthInLine小于文字长度,则说明这一行无法容下,需要换行,此时:

  • lines:加1
  • x:0
  • y:同上
  • w:同上
  • h:同上

通过以上的计算,所有的cell的frame都已经设定好了,那么剩下的事情就简单了:

告诉collection view,content size一共有多少:lines拿到了,当然知道content size了.

- (CGSize)collectionViewContentSize {
    CGFloat height = lines * kLineHeight + (lines - 1) * kLineSpace;
    return CGSizeMake(self.collectionView.bounds.size.width, height);
}

告诉collection view,在任意时刻,应该显示哪些cell:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *attributesArray = [@[] mutableCopy];
    for (UICollectionViewLayoutAttributes *attributes in self.cache) {
        if (CGRectContainsRect(rect, attributes.frame)) {
            [attributesArray addObject:attributes];
        }
    }
    return attributesArray;
}

每个cell都知道其frame,通过CGRectContainsRect方法进行对比,当frame在rect之中的时候,就添加进数组即可.

总结

这是一个最简单的layout实例,它还有更多更复杂,更灵活,更漂亮的排版布局.

更多的资料:

瞄大的文章1
瞄大的文章2

相关文章

  • UICollectionView-Part2

    接着上一篇文章,来做一个简单的排版试试看,demo下载地址 想要实现的效果 有不少的App实现了这种类似于关键字排...

网友评论

      本文标题:UICollectionView-Part2

      本文链接:https://www.haomeiwen.com/subject/xijycttx.html