iOS UICollectionView: Cells not showing

巧了我就是萌 提交于 2019-12-24 04:35:08

问题


I'm missing something obvious here as this isn't a difficult task.

I have my Collection view in storyboard (amongst other views), with the prototype cell's reuse id being "Cell", and a UILabel in that cell, with a tag of 100.

The code (boilerplate):

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    UILabel *label = (UILabel *)[cell viewWithTag:100];
    label.text = @"Hello";

    return cell;
}


The code is within a UICollectionViewController, as it should. When i run, the view appears yet no cells or text are visible.

A NSLog in the cellForItemAtIndexPath confirms that it is called, 4 times. I've even changed the prototype cell's background color which shows that not even the cell's are appearing.

In the viewDidLoad, it calls: [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

What am i missing?


回答1:


Use like this: Instead of registerClass: use registerNib:

static NSString *identifier = @"Cell";
if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {
    [self.collection registerNib:[UINib nibWithNibName:@"CollectionPhotoItem" bundle:nil] forCellWithReuseIdentifier:identifier];
}
else{
    [self.collection registerNib:[UINib nibWithNibName:@"CollectionPhotoItem_ipad" bundle:nil] forCellWithReuseIdentifier:identifier];
}



回答2:


make sure you are under any-any ratio in your storyboard if you are working with any other configuration and you tried to use the simulation it might not show up

for example if you use regular width and compact hight and then tried to use the simulator in your Xcode all your work will not show up !



来源:https://stackoverflow.com/questions/27837213/ios-uicollectionview-cells-not-showing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!