-2

This is the loop for:

I would like that add 3 images (called 1.jpg, 2.jpg, 3.jpg) to 3 rows that the table has. But with >= the view doesn´t appeared and with == only the first row has an image.

for (int i = 0; i >= indexPath.row; i++) {
        i++;
        NSString *number = [NSString stringWithFormat:@"%d", i];
        NSString *format = @".jpg";
        NSString *end= [NSString stringWithFormat:@"%@%@", number, format];
        cell.imageView.image = [UIImage imageNamed:end];
    }

What I have to do?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user1911
  • 680
  • 1
  • 14
  • 36

2 Answers2

3

Suppose you have your images like this:

0.jpg
1.jpg
2.jpg
...

Then you should do this in cellForRowAtIndexPath: delegate method:

NSString *imageName= [NSString stringWithFormat:@"%d.jpg", indexpath.row];
cell.imageView.image = [UIImage imageNamed:imageName];

No for loop, no appending.

Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46
1

Well there are many thing wrong with you code, first lets start with the first line in your loop.

i++ will increment the i which means you steps are 2 and not 1.

Second you are saying to keep looping while i is bigger or equal to indexPath.row, so if indexPath.row is 0 this loop will never end.

Third you do not need so many string, you can format it in one go

for (int i = 0; i < indexPath.row; i++) {
    NSString *imageName= [NSString stringWithFormat:@"%d.jpg", i+1];
    cell.imageView.image = [UIImage imageNamed:imageName];
}

But now you're just overriding the same image to get only the latest image show. If you want row 1 to have 1.jpg and row 2 2.jpg then a loop isn't needed at all. You can just assign the image directly:

NSString *imageName= [NSString stringWithFormat:@"%d.jpg", indexPath.row+1];
cell.imageView.image = [UIImage imageNamed:imageName];
rckoenes
  • 69,092
  • 8
  • 134
  • 166