1

我正在尝试动态创建 UICollectionView ,但我不断收到一个异常,我们通常在未设置 dataSource 或委托时遇到该异常:

* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[UIView collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 0x8a78ce0”

但它就在那里!这是我的代码:

标题:

#import <UIKit/UIKit.h>
@interface classHeader : UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>

@property(nonatomic, retain) UICollectionView *collectionView;

@end

执行:

#import "classHeader.h"


@implementation classHeader

@synthesize collectionView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];   

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection: UICollectionViewScrollDirectionHorizontal];
    [flowLayout setItemSize: CGSizeMake(0, 0, 10, 10)];

    collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 50, 50) collectionViewLayout:flowLayout];

    [collectionView setDelegate:self];
    [collectionView setDataSource:self];

[collectionView registerClass:[wbcGuidedAccessManualSlideCell class] forCellWithReuseIdentifier:SlideCellIdentifier];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    return 0; // No matter what value is here - exception
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
    return 0; // No matter what value is here - exception
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return nil; // No matter what value is here - exception
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO: Select Item
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO: Deselect item
}

#pragma mark – UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 20, 0, 20);
}

@end

还有一个有趣的注释:

  • 如果我使用情节提要使用其连接器设置 dataSource/delegate,我仍然必须通过代码设置 dataSource/delegate,所以我设置了两次,但它有效;
  • 当我仅使用代码或仅使用情节提要连接器时 - 它不起作用并且我得到异常。

我不明白我必须设置什么或实施更多?

PS XCode 5.0

4

0 回答 0