Reusability issue on UICollectionView

后端 未结 2 1175
既然无缘
既然无缘 2021-01-22 15:24

I had worked with UITableView but I have never ever use of UICollectionView in my apps. So I want to create UICollectionView programmatic

2条回答
  •  忘掉有多难
    2021-01-22 15:27

    You can do it with two way.

    Remove UILabel form view.

     - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
        for (UILabel *lbl in cell.contentView.subviews)
        {
            if ([lbl isKindOfClass:[UILabel class]])
            {
                [lbl removeFromSuperview];
            }
        }
        UILabel *lblCategoryTitle =[[UILabel alloc]init];
    
        [lblCategoryTitle  setFont: [UIFont fontWithName:@"OpenSans-Bold" size:14]];
        lblCategoryTitle.textAlignment = NSTextAlignmentCenter;
        lblCategoryTitle.frame = CGRectMake(3.5, 90, 90, 24);
        lblCategoryTitle.textColor = [UIColor blackColor];
        lblCategoryTitle.text = @"Product 1";
        lblCategoryTitle.backgroundColor = [UIColor clearColor];
        lblCategoryTitle.numberOfLines = 2;
        [cell.contentView addSubview:lblCategoryTitle];
        return cell;
    }
    

    Use tag to get Label

     - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
        UILabel *lblCategoryTitle =(UILabel *) [cell viewWithTag:5];
        if (!lblCategoryTitle) {
            lblCategoryTitle=[[UILabel alloc]init];
            [cell.contentView addSubview:lblCategoryTitle];
    
        }
        [lblCategoryTitle  setFont: [UIFont fontWithName:@"OpenSans-Bold" size:14]];
        lblCategoryTitle.tag=5;
        lblCategoryTitle.textAlignment = NSTextAlignmentCenter;
        lblCategoryTitle.frame = CGRectMake(3.5, 90, 90, 24);
        lblCategoryTitle.textColor = [UIColor blackColor];
        lblCategoryTitle.text = @"Product 1";
        lblCategoryTitle.backgroundColor = [UIColor clearColor];
        lblCategoryTitle.numberOfLines = 2;
        return cell;
    }
    

提交回复
热议问题