【xib】加载的一些问题,以UICollectionView 为例

xib 用不好在开发中很容易制造各种crash,issue像

1.[CUINamedImage collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 0x8c9a6d0
2.*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:]
3.[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:]

 

我想在一个ViewController中自定义一个View,这个View是collectionview

//.h文件
@interface ImageCollectionView : UICollectionView<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *imageCollection;
+(ImageCollectionView *)instanceTextView;
@end

//.m文件
#import "ImageCollectionView.h"
#import "ImageCollectionViewCell.h"

@implementation ImageCollectionView
+(ImageCollectionView *)instanceTextView
{
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"ImageCollectionView" owner:nil options:nil];
    return [nibView objectAtIndex:0];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
    }
    return self;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 12;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * CellIdentifier = @"CustomCollectCell";
    
    [_imageCollection registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    return cell;
    
}

//ImageCollectionViewCell 就不写了

  

在看xib

在image Collection View 中inspector 继承ImageCollectionView,

在collection View 中outlets 连image Collection View而不是File‘s owner (一般自带xib的控制器都是连File‘s owner)

 

上面是用xib自定义一个collectionView 的例子。

再看看 创建一个自带xib的ControllerView的情况:

File‘s owner 中custom class 是绑定控制器类AddGoodsController的,连一些协议也就是连 File‘s owner 。

 

 

所以,

1.绑定谁,谁就是self,可以在类中self.  

2.用xib 自定义view 出现上面的问题基本就是绑定关系的问题

3.xib技巧介绍

 

 

posted @ 2015-07-21 11:26  _yfan  阅读(708)  评论(0编辑  收藏  举报