Using a UICollectionView from a UICollectionViewCell

后端 未结 6 1591
感情败类
感情败类 2021-01-13 06:38

I have a custom UICollectionViewCell whose content is also a collection and I would like to use UICollectionView to display its content. Is this possible? How would I accomp

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 06:54

    Here is an example of how this can be done. We have a storyboard with a standard UITableViewController, a custom UITableViewCell, and a separate freeform custom 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;
    }
    

    The result is that the custom view controller responds to the button taps. It is not the case that the view lifecycle methods are called as the view appears and disappears from the table.

    I did this as a proof of concept, but for the project I'm working on I don't see any real advantage to having CellContentViewController be a view controller instead of just a custom view.

提交回复
热议问题