UIImageView无法在UICollectionViewCell中加载图像

时间:2015-04-02 11:33:54

标签: ios objective-c uiimageview uicollectionview

我是UICollectionViews的新手。我已经设置了一个基本的UICollectionViewController,其中包含2个单元格的行。在控制器中,我有一个单元格,我将UIImageView拖入其中。我将它连接到自定义单元类。我确保在接口构建器中也将单元的类更改为此类。在我的视图控制器中,我有这个代码:

@implementation StickersViewController

static NSString * const reuseIdentifier = @"stickerCell";

- (void)viewDidLoad {
    [super viewDidLoad];




    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];


    //Add the images
    self.images = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"one.png"], [UIImage imageNamed:@"two.png"], [UIImage imageNamed:@"three.png"], nil];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.images count];
}

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

    cell.imageView.image=self.images[indexPath.row];

    return cell;
}

运行代码时出现此错误: UICollectionViewCell imageView]:无法识别的选择器发送到实例0x7fe8e0e7828 。不知道为什么。似乎我已正确连接。有人可以给我一些指示我可能出错的地方吗?

2 个答案:

答案 0 :(得分:4)

问题在于:

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

您正在注册UICollectionViewCell而不是自定义子类。那应该是:

[self.collectionView registerClass:[StickerCell class] forCellWithReuseIdentifier:reuseIdentifier];

另外,请记住,如果在Storyboard中完成设置,您不需要自己注册该类,因为它会自动为您处理(前提是您已设置自定义类和重用标识符)

我希望这是有道理的

答案 1 :(得分:1)

参考本教程http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12
 你会得到正确的答案。可能我认为你没有设置集合可重用视图标识符
 选择集合视图单元格转到属性检查器并设置集合可重用视图标识符=单元格