【问题标题】:Exception when adding UICollectionViewController to UITabbarController将 UICollectionViewController 添加到 UITabbarController 时出现异常
【发布时间】:2015-06-12 16:43:16
【问题描述】:

我是 iOS 编程新手,希望您能帮助我。

我得到一个

'NSInvalidArgumentException'

当尝试将 UICollectionViewController 添加到我的 UITabbarController..

'UICollectionView 必须用非零布局参数初始化'

问题是我确实使用 FlowLayout 初始化了我的 CollectionView...这里是 MatchesCell 是我的 UICollectionViewCell 实现的代码

[self.collectionView registerClass:[MatchesCell class] forCellWithReuseIdentifier:@"MatchesCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 140)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView initWithFrame:[self.tabBarController.view frame]  collectionViewLayout:flowLayout];`

我还尝试使用 [[UIScreen mainScreen] bounds] 或我手动创建的 CGRect 调用 initWithFrame,但也没有用...请帮助!

提前致谢!

【问题讨论】:

  • 如何创建您的UICollectionViewController

标签: ios uicollectionview uitabbarcontroller collectionview


【解决方案1】:

看起来您可能正在初始化两个 UICollectionViewController。代码中的第一行是 [self.collectionView registerClass:...],这意味着在您到达代码的最后一行之前已经存在一个,即 [self.collectionView initWithFrame:.. collectionViewLayout:..]。

如果您在情节提要中制作集合视图,请仔细检查它的属性中是否设置了有效的布局,您可以在界面构建器的右侧面板中找到该布局。否则,在您访问此代码之前,请仔细检查您可能正在创建 UICollectionView 的任何地方的其余代码。任何 init 方法,viewDidLoad、viewWillAppear 或 viewDidAppear 都可能是开始的好地方。

最后,尝试添加一个异常断点,它有望向您显示应用程序崩溃的确切位置。 https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_an_exception_breakpoint.html

【讨论】:

    【解决方案2】:

    CollectionViewController初始化应该如下,

     UICollectionViewLayout *myLayout = [[UICollectionViewLayout alloc] init];        
    CollectionViewController *collectionViewController = [[CollectionViewController alloc] initWithCollectionViewLayout:myLayout];
    

    在“viewDidLoad”等CollectionViewController生命周期方法中,添加以下内容,

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];        
    self.view.backgroundColor = [UIColor whiteColor];    
    self.collectionView.backgroundColor = [UIColor clearColor];        
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];        
    flowLayout.itemSize = CGSizeMake(CGRectGetWidth(self.collectionView.frame)/2 - 20,     
    CGRectGetWidth(self.collectionView.frame)/2 - 20);
    self.collectionView.collectionViewLayout = flowLayout;
    

    这应该可以解决您的问题。 谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多