在使用UICollectionView的时候会出现在cell上添加视图后重用时视图重叠了,如果只是添加了一张图片在上面可能你不能发现,但添加了UILabel时你就能看到如下的效果,因为在初始化cell时不像UITableView一样调用init的一些方法,所以CollectionView是在init方法是就已经把视图初始化出来了,所以再添加就会重叠,一下2种方法以供使用。
方法一:移除contentView上的视图再添加视图
<span style="color:#333333;"><span style="font-size: 14px;">- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@“videoCell” forIndexPath:indexPath];
//移除contentView上的视图,不然会重叠
</span><span style="font-size:18px;"><strong> for (UIView *view in [cell.contentView subviews])
{
[view removeFromSuperview];
}</strong></span><span style="font-size: 14px;"><strong>
// <<<<</strong><<< cell上的视图配置
UIImageView * videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 2 * (cell.frame.size.height/3))];
videoImageView.image = [UIImage imageNamed:@"6.png"];
UILabel * titlePreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(videoImageView.frame) + 5, 40, 20)];
titlePreLabel.text = @"标题";
titlePreLabel.font = [UIFont systemFontOfSize:12];
UILabel * titleNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(titlePreLabel.frame), CGRectGetMinY(titlePreLabel.frame), 130, 20)];
titleNameLabel.text = @"世界高尔夫比赛决赛视频";
titleNameLabel.font = [UIFont systemFontOfSize:10];
UILabel * publishTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titlePreLabel.frame) + 5, cell.frame.size.width, 25)];
publishTimeLabel.text = @"2016-02-14";
publishTimeLabel.textAlignment = NSTextAlignmentCenter;
publishTimeLabel.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:videoImageView];
[cell.contentView addSubview:titlePreLabel];
[cell.contentView addSubview:titleNameLabel];
[cell.contentView addSubview:publishTimeLabel];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}</span></span>
方法二:新建UICollectionViewCell的类,在类中重写init方法初始化想要的视图
1: 首先创建一个类,集成 UICollectionViewCell,将你这个UIImageView加到这个类的init方法里面去
2: 在viewDidLoad的时候,注册重用 [self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"CELL"];
3: 使用 MyCommentsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];