如何在 NSArray 的 cell.imageview.image 上显示图像


Image Array=[NSArray arrayWithObjects:[UIImage imageNamed:@"1 (1).gif"],
            [UIImage imageNamed:@"1 (2).gif"],[UIImage imageNamed:@"1 (3).gif"],[UIImage imageNamed:@"1 (4).gif"],[UIImage imageNamed:@"1 (5).gif"],[UIImage imageNamed:@"1 (6).gif"],[UIImage imageNamed:@"1 (7).gif"],nil];
//here is another array of objects showing in table view
alphabetsArray =[[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
    //everything working fine until when i add this code,app crashes with SIGABRT
cell.imageView.image=[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];

其实我还需要问一些事情:

  1. 如果数组中的图像数不等于表视图中的对象数,是否有任何问题?
  2. 如果图像数量很大,除了 uiimage imageNamed:"随便.jpeg"
  3. 如果添加一个文件夹并给出其地址或名称,它会自己拾取图像怎么办。
  4. 如果图像数量为 250 个(即 sqlite、coreData、项目中的硬编码,那么在项目中添加图像的最合理方法是什么?

首先,此行[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]]存在问题。

[imageArray objectAtIndex:indexPath.row]在当前实现中返回 UIImage 对象,并且您正在尝试获取名称为 UIImage 对象的 UIImage。

您应该将 UIImage 对象直接返回到 cell.imageView.image。

cell.imageView.image = [imageArray objectAtIndex:indexPath.row];

其次,我不确定表中有多少行,但是如果索引超过数组中的元素数,则方法objectAtIndex可能会引发异常,从而导致应用程序崩溃。

1(这不会有问题,除非你想拥有相同的数字。它不会引发错误,但应用逻辑将无法正常工作。

2(不是我知道的,虽然这很容易做到,使用一个简单的命名约定,比如image01,这样你就可以复制粘贴代码并更改图像的结束数字

3(我不确定你在问什么。

4(通常,您只需通过drag-N'-drop或选择文件将图像添加到项目中。Core data 和 sqlite 适用于您正在开发的实际应用程序,而不是在 Xcode 中存储图像。

至于主要问题,您说要显示NSArray中的图像,如果是这种情况,只需获取表视图的索引路径,然后使用objectAtIndex:查找相应的图像

希望对:)有所帮助

其实我已经想通了一些办法,有一个简单的方法可以做到。

cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.gif", [TextShownInTableArray objectAtIndex:indexPath.row]]];

我在这个数组中有字母表,我想对每个字母表使用不同的图像,所以只是在项目中添加了与字母表同名的图像。 它与这行代码一起工作得很好。TextDisplayInTableArray 是包含文本:)的数组

Image Array=[NSArray  alloc]initWithObjects:[UIImage imageNamed:@"8.gif"],
        [UIImage imageNamed:@"2.gif"],[UIImage imageNamed:@"3.gif"],[UIImage imageNamed:@"6.gif"],[UIImage imageNamed:@"5.gif"],[UIImage imageNamed:@"4.gif"],[UIImage imageNamed:@"7.gif"],nil];

您的数组分配和该数组"保留"此数组并尝试此代码.谢谢

[imageArray retain];

只更改你的代码这一行。 并解决您的问题

cell.imageView.image=[imageArray objectAtIndex:indexPath.row];

我希望这段代码对您有用。检查这个

cell.imageView.frame = CGRectMake(5, 5, 50, 50);
NSString *imgstr = [[Arr objectAtIndex:indexPath.row] objectForKey:@"thumb"];
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgstr]]];

最新更新