UICollectionView - 不显示单元格

时间:2014-01-17 21:30:55

标签: ios objective-c ipad uicollectionview

我想要实现的是一个带有UICollectionView的3x3表。但它在运行应用程序时不会显示任何单元格。它确实显示CollectionView的背景颜色(我设置为蓝色)有人可以帮我吗?

我所做的是创建一个storyboard,然后只需将CollectionViewController拖到其上即可。该控制器还带有嵌套CollectionView。然后我只是使用设置使其背景为蓝色并添加一个单元格,我将背景设为紫色(两者仅用于测试)。最后将UILabel拖到它上面。现在运行时它只显示蓝色背景但没有单元格,即使它们在编辑器中清晰可见。然后我尝试创建自定义UICollectionViewController,将类分配给CollectionViewController而不是标准类,并对单元格执行相同操作(分配自定义UICollectionViewCell)。在自定义UICollectionViewController中,我实现了以下方法:

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

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    AboutYourGoalsMultiSelectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [[cell goal]setText:@"T"];

    return cell;
}

我将单元格的标识符设置为“Cell”,并在CollectionView和自定义UICollectionViewController之间建立了dataSource和委托的出口连接。一切都很好。 那我错过了什么?通过简单地使用编辑器进行所有这些调整之前,它不应该显示出某种方式吗?

The storyboard editor with all the changes I did

5 个答案:

答案 0 :(得分:47)

See my answer here,简而言之,如果您正在处理故事板,则需要删除此行

 // Register cell classes
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

答案 1 :(得分:6)

常见的错误来源是未在Outlets中设置dataSource和delegate

答案 2 :(得分:3)

您的代码的第一行有错误。

-(NSIntegear)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

NSIntegear应为NSInteger

不确定是否存在问题,因为xcode不允许您使用此错误运行项目。我只是尝试按照你提到的完全相同的步骤(没有标签),但通过上述修正,它对我来说很好。这是一个截图:

enter image description here

答案 3 :(得分:2)

由于我没有找到直接的解决方案,我试图建立一个新项目,并做了相同的更改和调整,令人惊讶的是,这一次,一切都从一开始就有效。然后我将故事板复制到我的旧项目中,删除了所有旧文件,并将其替换为新项目中的文件。到目前为止,一切都运转良好。我不知道实际的错误是什么,但我很高兴它现在正在工作。感谢所有看过我问题的人!

答案 4 :(得分:0)

如果您尝试创建一个简单的CollectionViewController(不是自定义的,即通过实现),并且您的单元格在应用程序运行时不显示,请按照以下步骤操作: -

  • 首先,你必须为你的UICollectionViewController创建可可触摸类(如果没有创建)。文件 - >新 - > COCOA TOUCH CLASS然后从子类的下拉列表中选择UICollectionViewController。
  • 现在,在您的CollectionViewController的身份检查员部分,通过从自定义类的下拉列表中选择来添加您的课程。
  • 现在打开您创建的课程并编辑您的方法:

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    //#warning Incomplete method implementation -- Return the number of sections
    return 1
     }
     override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //#warning Incomplete method implementation -- Return the number of items in the section
    return 1
    }
    
  • 仅编辑"返回" value(默认为0)只是简单地写下你想要显示或已经创建的单元格/项目的数量(在这种情况下,我只创建了一个单元格)。

[ios] [swift3] [xcode]