UICollectionView重用时的视图重叠

      在使用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];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值