71

当我尝试放入Interface BuilderUICollectionCellUICollectionView,我无法以未知的原因放入它。单元格将转到工具栏而不添加到UICollectionView

我在用:

  • iOS SDK 6.0
  • XCode 4.5.1
  • 我不使用情节提要
4

3 回答 3

143

只有 StoryBoard 中的 UICollectionView 内部有 UICollectionViewCell。如果使用 XIB,使用 CellName.xib 创建一个新的 XIB,将 CollectionViewCell 添加到其中,指定 UICollectionView 自定义类的名称。之后使用 registerNib。

示例代码:https ://github.com/lequysang/TestCollectionViewWithXIB

于 2013-03-03T11:09:40.667 回答
18

如果您正在使用文件,则不能UICollectionViewCell直接放入。它只可能在故事板中。将 a 添加到单独的 Xib 文件中。给出你的班级名称。然后在集合视图出现之前注册类或 xibUiCollectionViewXibUICollectionViewCell

 [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:CELL_ID];

通常这是在viewDidLoad.

这是UICollectionViewCell不使用的自定义的实现Xib

 @implementation CollectionViewCell
 @synthesize imageView = _imageView;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {

    self.backgroundColor = [UIColor whiteColor];
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowRadius = 5.0f;
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
    self.layer.shadowOpacity = 0.5f;

    // Selected background view
    UIView *backgroundView = [[UIView alloc]initWithFrame:self.bounds];
    backgroundView.layer.borderColor = [[UIColor colorWithRed:0.529 green:0.808 blue:0.922 alpha:1]CGColor];
    backgroundView.layer.borderWidth = 10.0f;
    self.selectedBackgroundView = backgroundView;

    // set content view
    CGRect frame  = CGRectMake(self.bounds.origin.x+5, self.bounds.origin.y+5, self.bounds.size.width-10, self.bounds.size.height-10);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    self.imageView = imageView;          
    [imageView release];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill ;
    self.imageView.clipsToBounds = YES;
    [self.contentView addSubview:self.imageView];       

}
return self;
 }
于 2013-03-03T11:08:54.753 回答
0

好的。实际上有一个解决方法,如果你真的想在 interface builder 的 xib 文件中的 collectionView 中拥有单元格:

  1. 创建故事板。
  2. 从界面生成器创建 UICollectionView 和 UICollectionViewCell。
  3. 使用约束等调整 UI,使其看起来完全符合您的要求。
  4. 创建一个新的 xib 文件。
  5. 将情节提要中的所有内容复制到新的 xib 文件中。

它将完美地工作。

  • One thing to keep in mind that step #3 is very important, because after #5 you are not supposed to drag and move around the UICollectionView, if you do, the cell will magically disappear! Other than that, it will just work perfectly.
于 2016-09-21T21:26:02.167 回答