如何将UICollectionView作为子视图添加到UIView?

时间:2014-02-02 18:42:15

标签: ios objective-c uiview uicollectionview lldb

好吧,我在编译这段代码时得到了(lldb)。我正在尝试将UICollectionView添加到Storyboard中的UIView中。这不对,对吧?

#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 个答案:

答案 0 :(得分:7)

将另一个控制器的视图添加为子视图通常不是一个好习惯,除非您还将该控制器添加为childViewController。因此,您可以将TLViewController添加为子项,或者只是添加UICollectionView作为子视图,并使MyViewController成为其数据源和委托。要将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];

我不确定这是否能解决您的问题,因为可能存在其他问题,但如果您想让TLViewController的视图成为MyViewController视图的子视图,您仍然应该这样做。

您也可以在没有代码的情节提要中执行此操作。您可以向MyViewController的视图添加容器视图,该视图将为您提供嵌入式控制器(默认情况下为UIViewController)。只需删除你得到的控制器,拖出一个UICollectionViewController,然后从容器视图中控制拖动到它,然后选择embed。如果你想从MyViewController获得对这个控制器的引用,你可以实现prepareForSegue,集合视图控制器将是segue.destinationViewController。