这几天在研究autolayout,原先做iOS应用的时候都是纯代码,storyboard和xib很少去碰他,这几天想尝试一下,结果遇到了各种坑。
今天在使用CollectionView的时候,发现用xib拉的控件无法显示,下面是我的步骤。
首先我使用xib进行布局(GoodsCell.xib)
它和GoodsCell.h、GoodsCell.m是关联的,并且我将每个控件都关联到.h文件中了,并且设置了Identifier为goodscell。
接下来,我在viewController里面注册了GoodsCell。 代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:@"GoodsCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier]; //注册了nib
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
}
#pragma mark - collectionView datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return goods.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
GoodsCell * cell = (GoodsCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
NSArray * good = goods[indexPath.row];
[cell.imageView sd_setImageWithURL:good[0] placeholderImage:[UIImage imageNamed:@"default.png"]];
[cell.nameView setText:good[1]];
[cell.priceView setText:[NSString stringWithFormat:@"¥%@",good[2]]];
cell.backgroundColor = [UIColor blackColor]; //为了看到效果,我将背景设置为黑色
DLog("%@",cell);
DLog("imageView%@",cell.imageView);
DLog("nameView%@",cell.nameView);
DLog("priceView%@",cell.priceView);
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(SCREEN_WIDTH/2,500); //为了看到效果,我将尺寸设的很大
}
本来以为这样就运行起来就可以了,但是我错了,cell虽然创建了,但是cell里面的imageView等控件却为空的。
效果如下:
可以看到,我再xib中定义的组件都不见了。
下面是我输出的几个对象:
[HomeViewController collectionView:cellForItemAtIndexPath:] [Line 71] <GoodsCell: 0x7fe0b360b7e0; baseClass = UICollectionViewCell; frame = (94 510; 187.5 500); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7fe0b3618c80>>
2015-12-04 15:24:32.118 YuanJing[96009:7164562] -[HomeViewController collectionView:cellForItemAtIndexPath:] [Line 72] imageView(null)
2015-12-04 15:24:32.118 YuanJing[96009:7164562] -[HomeViewController collectionView:cellForItemAtIndexPath:] [Line 73] nameView(null)
2015-12-04 15:24:32.118 YuanJing[96009:7164562] -[HomeViewController collectionView:cellForItemAtIndexPath:] [Line 74] priceView(null)
也就是说cell是创建了,但是子控件都是null,研究了很久还是没发现问题。求各路大神支招。
看不出来,你可以这么尝试下,看看有没有。在xib中给图像视图加上tag:10