6

我有一个自定义 UICollectionViewCell ,其内容也是一个集合,我想使用 UICollectionView 来显示其内容。这可能吗?我将如何做到这一点?我使自定义 UICollectionViewCell 也继承自 UICollectionViewDataSource 并定义了 UICollectionView 内部属性,但事情没有按预期工作。任何的想法?

4

6 回答 6

7

这是如何做到这一点的示例。我们有一个带有标准 UITableViewController、自定义 UITableViewCell 和单独的自由格式自定义 UIViewController 的故事板。

// ContainerCell.h
@class CellContentViewController;
@interface ContainerCell : UITableViewCell
@property (nonatomic, strong) CellContentViewController*  contentViewController;
@end

// CellContentViewController.h
@interface CellContentViewController : UIViewController
@property (nonatomic, weak) IBOutlet UILabel*   nameLabel;
@end

// CellContentViewController.m
@interface CellContentViewController ()    
- (IBAction)didTapButton:(UIButton*)sender;    
@end        
@implementation CellContentViewController           
- (void)didTapButton:(UIButton *)sender
{
    NSLog(@"Button for %@!", self.nameLabel.text);
}
@end

// MyTableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* const kCellIdentifier = @"ContainerCell";
    ContainerCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];        
    if (!cell.contentViewController)
    {
        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

        CellContentViewController* contentViewController= [storyboard instantiateViewControllerWithIdentifier:@"CellContentViewController"];

        cell.contentViewController = contentViewController;
        [cell.contentView addSubview:cell.contentViewController.view];
    }        
    cell.contentViewController.nameLabel.text = self.names[indexPath.row];                
    return cell;
}

结果是自定义视图控制器响应按钮点击。视图生命周期方法不会在视图出现和从表中消失时被调用。

我这样做是为了证明概念,但是对于我正在从事的项目,我认为拥有CellContentViewController一个视图控制器而不仅仅是一个自定义视图没有任何真正的优势。

于 2014-03-18T20:12:05.660 回答
4

这个有可能。通常,您将创建一个管理内部集合视图的视图控制器,并将此视图控制器的视图添加到外部集合视图的单元格的内容视图中。

您没有对您当前的尝试或遇到的问题进行任何描述,因此我无法提供更多信息。

于 2013-02-13T21:36:08.093 回答
3

正如 BrettThePark 所提到的,不可能将容器视图添加到情节提要中的 UICollectionVIew 原型单元格。

您可以做的是在情节提要中创建一个单独的视图控制器,并以编程方式将其添加到您在 UICollectionView 中使用的 UICollectionViewCell 子类中的视图中。这个视图控制器当然可以是一个 UICollectionViewController。

例子:

-(void)awakeFromNib 
{
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                         bundle: nil];
    UIViewController *controller = [mainStoryboard instantiateViewControllerWithIdentifier:@"MyUIViewController"];

    [self addSubview:controller.view];
}
于 2013-03-05T13:08:59.793 回答
1

这是一个UICollectionView内部的例子UICollectionViewCell

https://github.com/irfanlone/Collection-View-in-a-collection-view-cell

于 2016-04-12T01:10:15.890 回答
-1

据我了解,这是不可能的。

我尝试在情节提要中这样做并得到错误:

“容器视图不能放置在运行时重复的元素中”

于 2013-02-13T21:29:34.447 回答
-4

使您的UITableViewController内容为Static.

在此处输入图像描述

于 2014-04-24T06:37:24.913 回答