如何将UICollectionView作为子视图添加到UIView? [英] How do I add a UICollectionView to a UIView as a subview?
问题描述
嗯,我在编译这段代码时得到了(lldb)。我正在尝试将UICollectionView添加到Storyboard中的UIView中。这不对,对吗?
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
推荐答案
将另一个控制器的视图添加为子视图通常不是一个好习惯,除非您还将该控制器添加为childViewController。因此,您可以将TLViewController添加为子项,或者只是将UICollectionView添加为子视图,并使MyViewController成为其数据源和委托。要将TLViewController添加为子项,您应该这样做,
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];
我不确定这是否能解决您的问题,因为可能还有其他问题,但是您如果你想让TLViewController的视图成为MyViewController视图的子视图,你仍然应该这样做。
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.
你也可以在故事板中没有代码地执行此操作。您可以向MyViewController的视图添加容器视图,该视图将为您提供嵌入式控制器(默认情况下为UIViewController)。只需删除你得到的控制器,拖出一个UICollectionViewController,然后从容器视图中控制拖动到它,然后选择embed。如果你想从MyViewController获得对这个控制器的引用,你可以实现prepareForSegue,集合视图控制器将是segue.destinationViewController。
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.
这篇关于如何将UICollectionView作为子视图添加到UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!