如何以编程方式在uicollectionview中插入图像?

时间:2014-02-17 06:55:56

标签: ios iphone objective-c uicollectionview uicollectionviewcell

我对Objective-C很新,所以希望这一切都有意义。我在第一个回答中提供了代码Creating a UICollectionView programmatically ..它工作正常。现在我想在单元格中添加一些图片通过鼠标点击扩展。我搜索了许多教程,但都使用了nib文件或故事板文件。如何以编程方式完成此任务?

非常感谢任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分:0)

洛根建议:

{{1}}

请回顾和upvote:)

答案 1 :(得分:-1)

初学者阅读tutroial并首先了解以下链接和苹果文档

ios-programming-uicollectionview-tutorial-with-sample-code

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/Reference/Reference.html

像这种方法一样改变你的背景颜色

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];
    [self.view addSubview:recipeImageView];
    cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]];

    return cell;
}

输出:

enter image description here

答案 2 :(得分:-1)

注:

上面的代码错了!

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];
    [self.view addSubview:recipeImageView];
    cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]];

    return cell;
}

你分配(更好地分配ONCE unsung TAG ...)但是每次调用cellForItemAtIndexPath时代码都会添加子视图。