I would like to display UILabel "No result found" in cell ("HomeProductCell" as below") if no data in collectionview. How can I set for this label in cell? Please help.
Here is my code:-
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (section == 3) { //Product
if(_youLikeItem.count >0)
{
return _youLikeItem.count;
}
}
return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *gridcell = nil;
if (indexPath.section == 3) {
HomeProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HomeProductCellID forIndexPath:indexPath];
if(_youLikeItem.count > 0){
cell.productImage = [_youLikeItem[indexPath.row]valueForKey:@"image"];
cell.productName = [_youLikeItem[indexPath.row]valueForKey:@"name"];
cell.productPrice = [_youLikeItem[indexPath.row]valueForKey:@"price"];
gridcell = cell;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, collectionView.bounds.size.width, collectionView.bounds.size.height)];
noDataLabel.text = @"No product(s) available";
noDataLabel.textColor = [UIColor grayColor];
noDataLabel.font = PFR18Font;
noDataLabel.textAlignment = NSTextAlignmentCenter;
[cell addSubview:noDataLabel];
}
}
Make sure that you indicate that there's at least 1 item in section 3:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (section == 3) { //Product
if (_youLikeItem.count > 0) {
return _youLikeItem.count;
} else {
return 1;
}
}
return 0;
}
That will do the trick. If you want to be extra careful then in collectionView:cellForItemAtIndexPath:
you can change
if(_youLikeItem.count > 0){
to
if (indexPath.item < _youLikeItem.count) {
(N.B. For collection views you should use indexPath.item
, not indexPath.row
.)