[英]How do I add a UICollectionView to a UIView as a subview?
Well I'm getting a (lldb) while compiling this code. 好吧,我在编译这段代码时得到了(lldb)。 I'm trying to add a UICollectionView into a UIView in the Storyboard.
我正在尝试将UICollectionView添加到Storyboard中的UIView中。 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
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. 除非您还将该控制器添加为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.
因此,您可以将TLViewController添加为子项,或者只是添加UICollectionView作为子视图,并使MyViewController成为其数据源和委托。 To add TLViewController as a child, you should do this,
要将TLViewController添加为子项,您应该这样做,
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. 我不确定这是否能解决您的问题,因为可能存在其他问题,但如果您想让TLViewController的视图成为MyViewController视图的子视图,您仍应该这样做。
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).
您可以向MyViewController的视图添加容器视图,该视图将为您提供嵌入式控制器(默认情况下为UIViewController)。 Just delete the controller you get, drag out a UICollectionViewController, and control-drag from the container view to it, and choose embed.
只需删除你得到的控制器,拖出一个UICollectionViewController,然后从容器视图中控制拖动到它,然后选择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.
如果你想从MyViewController获得对这个控制器的引用,你可以实现prepareForSegue,而集合视图控制器将是segue.destinationViewController。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.