接著上一篇文章,來做一個(gè)簡單的排版試試看,demo下載地址
想要實(shí)現(xiàn)的效果
有不少的App實(shí)現(xiàn)了這種類似于關(guān)鍵字排列的的效果,如圖:
對(duì)于這種排版的規(guī)則是什么呢?在不考慮文字換行,并且文字的長度超過container的長度的情況下,那么規(guī)則就是文字橫向排列:如果該行的剩余長度大于文字的長度,那么就排列上去;如果該行的剩余長度小于文字長度,那么就換行.
咱們來擼碼
創(chuàng)建一個(gè)工程balabala...
然后創(chuàng)建一個(gè)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];
沒有什么奇怪的東西,因?yàn)槭莇emo,所以直接使用了frame.當(dāng)然auto layout更好啦~=.=
但是有一個(gè)小問題,這個(gè)初始化collection view的layout是什么東東呢?呃是咱們自己定義的layout所以在初始化collection view之前,還有這樣一段代碼
CustomLayout *layout = [[CustomLayout alloc] init];
layout.delegate = self;
暫時(shí)放下layout,我們寫點(diǎn)很熟悉的代碼.
初始化測試數(shù)據(jù):
- (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"]];
}
幾個(gè)不可缺少的代理方法:
- (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是很簡單的,里面就包含了一個(gè)UILabel,用于顯示文字.
CustomLayout
排版的關(guān)鍵在于這個(gè)layout,首先定義了幾個(gè)常量:
#define kLeftMargin (5)
#define kLineSpace (10)
#define kLineHeight (17)
分別表示cell之間的水平間隔,每一個(gè)cell的高度,cell之間的垂直間隔.
也定義了一個(gè)delegate,用于獲取每一個(gè)cell的寬度:根據(jù)文字來計(jì)算寬度:
@protocol CustomLayoutDelegate <NSObject>
- (CGFloat)collectionView:(UICollectionView *)collectionView widthForTextAtIndexPath:(NSIndexPath *)indexPath;
@end
準(zhǔn)備工作做好了以后,我們開始著手核心的layout計(jì)算:
- (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];
}
}
}
我們通過一個(gè)屬性lines來知道一共有多少行,所以它初始化應(yīng)該為1.
我們需要知道一共有多少個(gè)數(shù)據(jù),所以直接通過collection view獲取到.
我們對(duì)每一個(gè)數(shù)據(jù),都需要對(duì)比文字長度和這一行的剩余長度,所以有一個(gè)leftWidthInLine變量來保存每一行的剩余長度.
循環(huán)遍歷所有的數(shù)據(jù),通過CustomLayoutDelegate可以獲取到每一個(gè)數(shù)據(jù)(文字)的長度.
如果leftWidthInLine大于文字長度,說明這一行能夠容下,不需要換行.那么這行的frame為:
- x:collection view的寬度減去leftWidthInLine
- y:(lines(總行數(shù)) - 1) * (每一行的高度+每一行的垂直間隔)
- w:代理獲取到的文字長度
- h:已經(jīng)定義好的每一行的高度
如果leftWidthInLine小于文字長度,則說明這一行無法容下,需要換行,此時(shí):
- lines:加1
- x:0
- y:同上
- w:同上
- h:同上
通過以上的計(jì)算,所有的cell的frame都已經(jīng)設(shè)定好了,那么剩下的事情就簡單了:
告訴collection view,content size一共有多少:lines拿到了,當(dāng)然知道content size了.
- (CGSize)collectionViewContentSize {
CGFloat height = lines * kLineHeight + (lines - 1) * kLineSpace;
return CGSizeMake(self.collectionView.bounds.size.width, height);
}
告訴collection view,在任意時(shí)刻,應(yīng)該顯示哪些cell:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray *attributesArray = [@[] mutableCopy];
for (UICollectionViewLayoutAttributes *attributes in self.cache) {
if (CGRectContainsRect(rect, attributes.frame)) {
[attributesArray addObject:attributes];
}
}
return attributesArray;
}
每個(gè)cell都知道其frame,通過CGRectContainsRect方法進(jìn)行對(duì)比,當(dāng)frame在rect之中的時(shí)候,就添加進(jìn)數(shù)組即可.
總結(jié)
這是一個(gè)最簡單的layout實(shí)例,它還有更多更復(fù)雜,更靈活,更漂亮的排版布局.
更多的資料: