代替UICollectionView出现了黑屏幕

26

我正在尝试重新实现无限滚动的UICollectionView,可以在这里看到。我发现缺少以下内容:

ViewController.h:

@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate>

@end

DataCell.h:

@interface DataCell : UICollectionViewCell
@property (nonatomic, strong) UILabel *label;
@end

DataCell.m:

#import "DataCell.h"

@implementation DataCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self){
        self.label = [[UILabel alloc] initWithFrame:self.bounds];
        self.autoresizesSubviews = YES;
        self.label.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                       UIViewAutoresizingFlexibleHeight);
        self.label.textAlignment = NSTextAlignmentCenter;
        self.label.adjustsFontSizeToFitWidth = YES;

        [self addSubview:self.label];
    }

    return self;
}

@end

CustomCollectionView.h:

@interface CustomCollectionView : UICollectionView

@end
整个项目我使用了一个storyboard和一个普通的UIViewController。在这个视图控制器上,我在Interface Builder中添加了一个UICollectionView。我将集合视图的出口与我的视图控制器连接,并再次设置数据源和委托方法。我还在Interface Builder中设置了UICollectionViewCell的自定义类和重用标识符。
所以一切都应该正常工作,但我只得到一个黑屏。我漏掉了什么?你可以在此处下载整个项目:here
6个回答

25

你正确地配置了CollectionView,只是忘记了标签的颜色 :)

    [self.label setTextColor:[UIColor whiteColor]];

这里输入图像描述

希望对你有所帮助!


6

在Storyboard中,您需要手动设置集合视图的背景颜色。

默认情况下,它是黑色的(尽管在Storyboard编辑器中不显示)

enter image description here


如果你想让背景清晰,你必须使用 collectionView.backgroundColor = [UIColor clearColor];collectionView.backgroundView = [[UIView alloc] initWithFrame:CGRectZero]; - highboi

4
我曾经遇到过同样的问题。黑屏似乎是集合视图没有可用数据的指示器。尝试更改集合视图的背景颜色,如果更改的颜色得以显示,那么您的集合视图是有效的。然后向集合视图添加一些带标签的imageview(例如,为图像视图分配值100),并使用cellforItemAtIndexPath将图像设置为图像视图。 (您可以使用自定义单元格来实现此操作。但现在,为了使集合视图正常工作,使用标签为图像视图分配值的方法更适合)
UIImageView * ImageView = (UIImageView *)[cell viewWithTag:100];
ImageView.image = [UIImage imageNamed:[images objectAtIndex:indexPath.row]];

2
[self.collectionView registerNib:[UINib nibWithNibName:@"ProductCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ProductCollectionViewCell"];

self.collectionView.backgroundColor = [UIColor clearColor];

2

我曾经遇到过一个问题,就是collectionView和collectionView cell的背景都是透明的。


1
在 Swift 中,
self.label.textColor = UIColor.whiteColor()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接