UICollectionView shows only the first item

前端 未结 4 946
灰色年华
灰色年华 2020-12-22 07:02

I\'m working on a project similar to a video album. In that I\'m using UICollectionView to display the thumb images of those videos. The worst part is that I sh

4条回答
  •  甜味超标
    2020-12-22 07:43

    you should never create ui elements in cellForRowAtIndexPath:. Subclass a collection view cell like so:

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            NSLog(@"INIT WITH FRAME FOR CELL");
            //we create the UIImageView here
            imageView = [[UIImageView alloc] init];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.frame = CGRectMake(cell.frame.origin.x , cell.frame.origin.y, cell.frame.size.width, (cell.frame.size.height - cell.frame.size.height/3));
            [self.contentView addSubview:imageView]; //the only place we want to do this addSubview: is here!
        }
        return self;
    }
    

    Then add that subclassed cell as a property and alter this code:]

    [collectionView registerClass:[customCellClass class] forCellWithReuseIdentifier:@"MyCell"];
    

    The perform these changes:

    -(customCellClass *) collectionView:(UICollectionView *)cV cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
       UICollectionViewCell *cell = (customCellClass *)[cV dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    
        cell.backgroundColor = [UIColor blackColor];
    
        imageView.image = [UIImage imageNamed:[storeData objectAtIndex:indexPath.row]];
    
        return cell;
    }
    

    A final adjustment would be to move the the [super viewDidLoad] to this:

    - (void)viewDidLoad
    {
         [super viewDidLoad];
         //insert the rest of the code here rather than before  viewDidLoad
    }
    

提交回复
热议问题