您的位置:首页 > 产品设计 > UI/UE

通过Xib创建 UICollectionView 和自定义UICollectionViewCell

2016-04-03 17:50 399 查看
1。在控制器的viewDidLoad方法中添加代码

CGFloat itemWidth = (kScreenW - kSpacingW * 3) / 2;

NSLog(@"itemWidth == %f",itemWidth);

CGFloat itemHeight = itemWidth * 0.75 + 71;

NSLog(@"itemWidth == %f",itemHeight);

UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc]init];

layout.itemSize = CGSizeMake(itemWidth, itemHeight);

layout.minimumInteritemSpacing = kSpacingW;

layout.minimumLineSpacing = kSpacingW;

layout.sectionInset = UIEdgeInsetsMake(0, kSpacingW, 0, kSpacingW);

self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

[self.view addSubview:self.collectionView];

self.collectionView.dataSource = self;

self.collectionView.delegate = self;

self.collectionView.backgroundColor = [UIColor whiteColor];

[self.collectionView registerClass:[HotCell class] forCellWithReuseIdentifier:@"HotCell"];

2.实现collectionView的代理方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

return 10;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

HotCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotCell" forIndexPath:indexPath];

cell.backgroundColor = [UIColor whiteColor];

return cell;

}

3.通过XIB自定义cell

- (instancetype)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

// 初始化时加载collectionCell.xib文件

NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"HotCell" owner:self options:nil];

// 如果路径不存在,return nil

if (arrayOfViews.count < 1) {

return nil;

}

// 如果xib中view不属于UICollectionViewCell类,return nil

if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {

return nil;

}

// 加载nib

self = [arrayOfViews objectAtIndex:0];

}

return self;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: