mardi 5 mai 2015

Add different images to UIImageView of cells in UITableView

Needless to say, i am a novice. I am trying to add images and text to a UITableView. I have been able to add the text but I am having problems with adding different images to the desired text.

I have 2 separate PHP codes for 1 database:

  • The first gets the text and an id for the image assigned to the text (imageID)
  • The second uses the id (from the first PHP) to acquire the image

My code is fine but currently only 1 image is appearing for all the text

My question is how do I assign each image to their text ?

And how do I not assign an image to the text that do not have images as some of the texts don't have images with them?

My code is as follows:

Connection and data download:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations
        NSMutableArray *list = [[NSMutableArray alloc] init];

    // Parse the JSON that came in
    NSError *error;
    jsonArray = [NSJSONSerialization JSONObjectWithData:downloadedData options:NSJSONReadingAllowFragments error:&error];

    // Loop through Json objects, create question objects and add them to our questions array
    for (int i = 0; i < jsonArray.count; i++)
    {
        jsonElement = jsonArray[i];

        // Create a new cell object and set its props to JsonElement properties
        if (![jsonElement [@"Thought"] isEqual:[NSNull null]])
        {
            NSString *listText =jsonElement [@"Thought"];
            if ([listText length] > 0)
            {
                NSString *cellText = jsonElement[@"Thought"];
                [list addObject:cellText];
                NSLog(@"list Cell: %@", cellText);
            }

            if (![jsonElement [@"filename"] isEqual:[NSNull null]])
            {
                imageID = jsonElement[@"id"];
            }
            NSLog(@"Cell Image: %@", imageID);
        }
    }
    [[self tableView1] reloadData];
}

Cells in the table:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleIdentifier = @"SimpleIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
    }

    cell.textLabel.text = [list objectAtIndex:indexPath.row];
    cell.textLabel.font = [UIFont italicSystemFontOfSize:20];

    if ([imageID length] > 0)
    {
        urlStr = [NSString stringWithFormat:@"http://ift.tt/1QgEkJ2", imageID];
        NSURL *imageUrl = [NSURL URLWithString:urlStr];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
        cell.imageView.image = imageLoad;
    }

    return cell;
}

Aucun commentaire:

Enregistrer un commentaire