【问题标题】:How do I add a UICollectionView to a UIView as a subview?如何将 UICollectionView 作为子视图添加到 UIView?
【发布时间】:2014-02-26 04:29:15
【问题描述】:

我在编译这段代码时得到了一个 (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

【问题讨论】:

    标签: ios objective-c uiview uicollectionview lldb


    【解决方案1】:

    将另一个控制器的视图添加为子视图通常不是一个好习惯,除非您还将该控制器添加为 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,然后从容器视图中按住 control 拖动到它,然后选择嵌入。如果你想从 MyViewController 中获取对这个控制器的引用,你可以实现 prepareForSegue,集合视图控制器就是 segue.destinationViewController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多