将存储在 NSArray 中的图像添加到 UITableView [英] Adding images stored in NSArray to UITableView

查看:75
本文介绍了将存储在 NSArray 中的图像添加到 UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是编程新手,我试图制作一个具有 UITableView 并显示存储在数组中的名称的应用程序,并在每个名称之外显示图像(图标).我在包中添加了三张图片,并将它们命名为 1.jpg2.jpg3.jpg.

First of all I'm new to programming and I was trying to make an app that has a UITableView and displays names that are stored in an array and displays images (icons) besides every name. I have added three images in the bundle and named them 1.jpg, 2.jpg and 3.jpg.

该应用程序运行良好,但在告诉应用程序我想显示存储在数组中的图像并运行该应用程序后,iOS 模拟器首先可以工作,但是我的 main.m 文件中出现绿色错误?

The app works well, but after telling the app that I want to display the images that are stored in the array and run the app the iOS simulator works at first but then I get a green error in my main.m file?

以下是我的实现文件:

NSMutableArray *myImages;
NSMutableArray *myNames;

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    myNames = [[NSMutableArray alloc ]initWithObjects:@"A",@"B",@"C", nil];

    for (int imageNumber =1 ; imageNumber <= 3; imageNumber++) {
            myImages= [[NSMutableArray alloc]initWithObjects:[[NSString stringWithFormat:@"%i.jpg", imageNumber ]], nil];
      }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return myNames.count;
 }


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];

     cell.textLabel.text = myNames[indexPath.row];

    //everything works fine until i add this line

    cell.imageView.image = myImages [indexPath.row];
    return cell;
}

推荐答案

您的图像名称数组应与名称数组的长度相匹配.将它们都配置为文字并尝试.也就是说,像这样初始化数组:

Your image name array should match the length of the names array. Configure them both as literals and try. That is, initialize the arrays like this:

NSArray *myNames = @[@"A", @"B", @"C"];
NSArray *myImages = @[@"1.jpg", @"2.jpg", @"3.jpg"];

您也可以通过更改图像循环来修复它,这样它就不会在每次迭代时都创建新的 NSMutableArray:

You can also fix it by changing your image loop so that it doesn't create a new NSMutableArray on every iteration:

myImages = [NSMutableArray array];
for (int imageNumber =1 ; imageNumber <= 3; imageNumber++) {
    [myImages addObject:[NSString stringWithFormat:@"%i.jpg", imageNumber]];
}

请注意,您需要使用图像名称创建图像:

Note that you'll need to create an image using the image name:

UIImage *actualImage = [UIImage imageNamed:myImages[indexPath.row]];

这篇关于将存储在 NSArray 中的图像添加到 UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆