我试图动态地创建UICollectionView但我不断收到异常,当数据源或委托未设置,我们通常会得到:
*终止应用程序由于未捕获的异常 'NSInvalidArgumentException',原因: ' - [UIView的的CollectionView:numberOfItemsInSection:]:无法识别的选择发送到实例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
而一个有趣的说明:
- 如果我用故事板利用其连接器来设置数据源/委托我还是通过代码来设置数据源/代表,所以我把它的两倍,但它的工作原理;
- 当我使用的代码而已,或者故事板的连接器使用 - 它不工作,我得到异常。
我不明白我必须建立或实施更多?..
PS的XCode 5.0