个人在做新特性界面时,时长会犯的错误,总结一下,希望对大家有帮助.
1.如果我们使用的是storyboard中的CollectionView,它的布局继承的是
UICollectionViewFlowLayout;大部分情况下我们会用到它;CollectionView中的cell没有UILable,UIImageView等控件,所以一般我们会自定义cell,并创建相应的xib来注册注册重用的cell
[self.collectionView registerNib:[UINib nibWithNibName:@"MyCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
如果不需要自定义cell则用:
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
还有一些常用属性:
// 1.设置分页
self.collectionView.pagingEnabled = YES;
// 2.去除滚动条
self.collectionView.showsHorizontalScrollIndicator = NO;
// 3.去除回弹效果
self.collectionView.bounces = NO;
2.一定不要忘了设置cell大小
#import <UIKit/UIKit.h>
@interface MyLayout : UICollectionViewFlowLayout
@end
#import "MyLayout.h"
@implementation MyLayout
-(void)prepareLayout {
self.itemSize = CGSizeMake(375, 667);
//设置滚动方向为水平滚动
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// self.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
}
@end
3.自定义布局:下面是我自定义布局实现的效果,需用到下面两个方法
#import "MyCircleLayout.h"
@implementation MyCircleLayout
//设置cell布局
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray *arrayM = [NSMutableArray array];
// 获取section对应的cell的总数
NSUInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i = 0; i< count; i++) {
//创建i位置cell的对应的IndexPath
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
// 创建i位置cell的属性
UICollectionViewLayoutAttributes *atts = [self layoutAttributesForItemAtIndexPath:indexPath];
[arrayM addObject:atts];
}
return arrayM;
}
//返回indexPath对应cell 的布局属性
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
NSInteger count = [self.collectionView numberOfItemsInSection:indexPath.section];
// 半径
CGFloat radius = 100;
CGFloat centerX = self.collectionView.frame.size.width * 0.5;
CGFloat centerY = self.collectionView.frame.size.height * 0.5;
// 单位旋转角度
CGFloat rota = 2 * M_PI / count;
// 创建i位置对应cell属性
UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attrs.size = CGSizeMake(50, 50);
if (count == 1) {
attrs.center = CGPointMake(centerX, centerY);
} else {
CGFloat angle = rota * indexPath.item;
// cell中心坐标
CGFloat attrsCenterX = centerX + radius * cos(angle);
CGFloat attrsCenterY = centerY + radius * sin(angle);
attrs.center = CGPointMake(attrsCenterX, attrsCenterY);
}
return attrs;
}
@end