在UICollectionView中实现图像下的标题

时间:2016-10-19 06:41:37

标签: ios uicollectionview

#import "ViewController.h"

@interface ViewController ()    
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
         static NSString *identifier = @"Cell";
    self.imageArray=[NSArray arrayWithObjects:@"1.png",@"2.png",@"3.jpeg",@"4.jpeg",@"1.png",@"2.png",@"3.jpeg",@"4.jpeg", nil];
    self.imageText=@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8"];
    // for image 

    UIImageView *recipeImageView = [[UIImageView alloc] init];
    recipeImageView.frame = self.collectionView.bounds;
    [self.collectionView addSubview:recipeImageView];
    recipeImageView.tag = 100;
    // for the label

    UILabel *title=[[UILabel alloc]init];
    title.tag = 200;
    [self.collectionView addSubview:title];

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];

}    

//to set the number of sections in UICOLLECTIONVIEW

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArray.count;
}

//To set the content to the UICollectionView

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
     static NSString *identifier = @"Cell";

        UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

//to set the image dynamically to the UICollectionViewCell

        UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
        recipeImageView.image = [UIImage imageNamed:[self.imageArray objectAtIndex:indexPath.row]];

        [self.view addSubview:recipeImageView];
        cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[self.imageArray objectAtIndex:indexPath.row]]];

//to set the label dynamically to the UICollectionViewCell

    UILabel *imageTitle=(UILabel *)[cell viewWithTag:200];

    [imageTitle setText:self.imageText];            
    return cell;     
}

@end 

0 个答案:

没有答案