问题
Well I'm getting a (lldb) while compiling this code. I'm trying to add a UICollectionView into a UIView in the Storyboard. This isn't right, right?
#import "MyViewController.h"
#import "TLSpringFlowLayout.h"
#import "TLViewController.h"
@interface MyViewController ()
@end
@implementation MyViewController
@synthesize collectionViewController;
- (void)viewDidLoad
{
[super viewDidLoad];
//I'm creating my UICollectionViewController by using TLViewController & the layout TLStringFlowLayout
collectionViewController = [[TLViewController alloc] initWithCollectionViewLayout:[[TLSpringFlowLayout alloc] init]];
[self.view addSubview:collectionViewController.view];
}
@end
回答1:
It's not generally a good practice to add the view of another controller as a subview, unless you also add that controller as a childViewController. So you can either add TLViewController as a child, or just add a UICollectionView as a subview, and make MyViewController its data source and delegate. To add TLViewController as a child, you should do this,
collectionViewController = [[TLViewController alloc] initWithCollectionViewLayout:[[TLSpringFlowLayout alloc] init]];
[self addChildViewController: collectionViewController];
[collectionViewController didMoveToParentViewController:self];
collectionViewController.view.frame = CGRectMake(0,0,200,400); //put whatever numbers you want to position and size the collection view
[self.view addSubview:collectionViewController.view];
I'm not sure whether this will fix your problem, because there might be other problems, but you should still do this if you want to make the the TLViewController's view a subview of MyViewController's view.
You can also do this in the storyboard with no code. You can add a container view to MyViewController's view which will give you an embedded controller (a UIViewController by default). Just delete the controller you get, drag out a UICollectionViewController, and control-drag from the container view to it, and choose embed. If you want to get a reference to this controller from MyViewController, you can implement prepareForSegue, and the collection view controller will be the segue.destinationViewController.
来源:https://stackoverflow.com/questions/21514617/how-do-i-add-a-uicollectionview-to-a-uiview-as-a-subview