Ios UICollectionView和一个视图控制器中的其他视图

Ios UICollectionView和一个视图控制器中的其他视图,ios,cocoa-touch,uicollectionview,Ios,Cocoa Touch,Uicollectionview,我有一个带rootViewController的iOS应用程序。在此视图控制器中有许多不同的视图。现在,我希望在此视图中有一个集合视图。我该怎么做?我试过的是。将uicollection视图添加到情节提要,并将数据源和委托设置为新的uicollectionview控制器。基本的东西是有用的。但是我无法从uicollectionview控制器视图访问collectionview。self.collectionview。我忘了什么吗?或者有更好的方法来处理此问题吗?如果希望由根视图控制器(即其视图层

我有一个带rootViewController的iOS应用程序。在此视图控制器中有许多不同的视图。现在,我希望在此视图中有一个集合视图。我该怎么做?我试过的是。将uicollection视图添加到情节提要,并将数据源和委托设置为新的uicollectionview控制器。基本的东西是有用的。但是我无法从uicollectionview控制器视图访问collectionview。self.collectionview。我忘了什么吗?或者有更好的方法来处理此问题吗?

如果希望由根视图控制器(即其视图层次结构的一部分)管理集合视图,请忘记集合视图控制器,设置集合数据源并委托给根视图控制器。然后在根视图控制器类中实现集合视图数据源和委托协议。

您应该使用普通视图控制器,而不是集合视图控制器。后者将集合视图作为其顶级
视图
属性,因此在向其中添加其他视图时灵活性较低

如果您想要
self.collectionView
您需要声明一个属性。别忘了在interface builder中连接它(加上委托和数据源)

当然,您可以对多个集合视图执行相同的操作。但是,在您的
UICollectionViewDataSource
和委托方法中,您必须区分两个集合视图,并提供各自的数据,或者根据使用的集合视图对用户交互作出反应

@interface ViewController ()
@property (nonatomic, strong) IBOutlet UICollectionView *collectionView;
@end

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

        UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
        [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setItemSize:CGSizeMake(200, 200)];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        [self.collectionView setCollectionViewLayout:flowLayout];
在cellForItemAtIndexPath中。。应该是下面这样的东西

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
    NSString *cellData = [data objectAtIndex:indexPath.row];
    static NSString *cellIdentifier = @"cvCell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
    [titleLabel setText:cellData];
   return cell;
}
参考下面的文章,很好地解释。

但如果我添加第二个uicollectionview,会发生什么?大概您也会更新控制器来管理它?听起来你在这个屏幕上有很多事情要做,不过。。。也许你可以再解释一下你的应用程序?谢谢你的回答!请注意,您应该将答案的重要部分发布在此网站上,否则您的帖子可能会被删除。如果您愿意,您可以继续添加该链接,但仅作为“参考”。答案应该是独立的,不需要链接。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
    NSString *cellData = [data objectAtIndex:indexPath.row];
    static NSString *cellIdentifier = @"cvCell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
    [titleLabel setText:cellData];
   return cell;
}