Установка изображения в UIImageView внутри ячейки табличного представления - PullRequest
0 голосов
/ 25 мая 2011

Я загружаю некоторые изображения, используя NSThread. Когда все изображения загружены, я должен поместить их в cell.myimageview. Дайте мне решение для установки изображения в пользовательском методе.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    static NSString *CellIdentifier = @"Cell";
    TableCell *cell = (TableCell *)[TableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[TableCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    }


    NSString *bedsbaths=[NSString stringWithFormat:@"Beds:%@ Baths:%@",[[AppDeleget.statuses valueForKey:@"beds"] objectAtIndex:indexPath.row],[[AppDeleget.statuses valueForKey:@"baths"] objectAtIndex:indexPath.row]];
    cell.mlsno.text=[[AppDeleget.statuses valueForKey:@"mlsno"] objectAtIndex:indexPath.row];
    cell.price.text=[[AppDeleget.statuses valueForKey:@"price"] objectAtIndex:indexPath.row];
    cell.address.text=[[AppDeleget.statuses valueForKey:@"address"] objectAtIndex:indexPath.row];
    cell.bedsbaths.text=bedsbaths;
    cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
return cell;

}
-(void)LoadImage
{
    for(int x=0;x<[ListPhotos count];x++)
    {   
        NSData *imageData =[ListPhotos objectAtIndex:x]; 
        id path = imageData;
        NSURL *url = [NSURL URLWithString:path];
        NSLog(@"%@",url);
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [[UIImage alloc] initWithData:data];
        [self performSelectorOnMainThread:@selector(downloadDone:) withObject:img waitUntilDone:NO];
    }

}
-(void)downloadDone:(UIImage*)img {

    // I have to set the cell here. How?        
    cell.myimageView.image=img
}

Ответы [ 5 ]

2 голосов
/ 26 апреля 2013

В содержащем контроллере вида

В методе tableView: cellForRowAtIndexPath: при создании новой ячейки укажите код:

cell.imageView.image = [UIImage imageNamed@"name of image.png"];

0 голосов
/ 10 января 2012

В вашем cellForRowAtIndexPath

UIImageView *logoImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 55)];
logoImgView.backgroundColor = [UIColor clearColor];
 [cell.Imageview addSubview:logoImgView];
 NSMutableArray *arrChng = [[NSMutableArray alloc] init];
 [arrChng addObject:logoImgView];
 [arrChng addObject:[Array objectAtIndex:indexPath.row];
 [self performSelectorInBackground:@selector(setImagesAfterShow:) withObject:arrChng];


-(void)setImagesAfterShow:(NSMutableArray *)array
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:[array objectAtIndex:1]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImageView *img = [array objectAtIndex:0];
img.image = [UIImage imageWithData:data];
[pool release];
}

этот метод используется для загрузки изображений в бэкэнд, поэтому легко сглаживать прокрутку таблицы

Еще один метод с использованием ASIHTTPRequest, в котором изображения загружаются в бэкэнди это очень хорошо, используйте ссылку .Это может быть полезно для вас.

0 голосов
/ 25 мая 2011

Даже если вы сможете установить его методом downloadDone:, позже вы столкнетесь с проблемой из-за многократного использования ячеек. Таким образом, правильное место для установки изображения будет само tableView:cellForRowAtIndexPath:. Так как вы загружаете изображения? Сохраните их в массиве или словаре. Скажем, количество не меняется, мы можем использовать объект NSMutableArray для хранения количества счетчиков NSNull одноэлементных объектов и более поздних,

в tableView:cellForRowAtIndexPath:

if ( [[images objectAtIndex:indexPath.row] isMemberOfClass:[UIImage class]] ) {
    cell.myImageView.image = [images objectAtIndex:indexPath.row];
}

in LoadImage

for(int x=0;x<[ListPhotos count];x++)
{   
    ... 
    [photos replaceObjectAtIndex:x withObject:image];
    [self performSelectorOnMainThread:@selector(downloadDone:) 
                           withObject:[NSNumber numberWithInt:x];
                        waitUntilDone:NO];
}

в downloadDone:

- (void)downloadDone:(NSNumber *)row {

    [self.tableView reloadRowsAtIndexPaths:[NSIndexPath indexPathForRow:[row intValue] inSection:0]
                          withRowAnimation:UITableViewRowAnimationTop];
}
0 голосов
/ 10 января 2012

Вы можете установить изображение для представления Image в самом методе cellForRowAtIndexPath.Попробуйте следующий код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


    static NSString *CellIdentifier = @"Cell";
    TableCell *cell = (TableCell *)[TableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[TableCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    }


    NSString *bedsbaths=[NSString stringWithFormat:@"Beds:%@ Baths:%@",[[AppDeleget.statuses valueForKey:@"beds"] objectAtIndex:indexPath.row],[[AppDeleget.statuses valueForKey:@"baths"] objectAtIndex:indexPath.row]];
    cell.mlsno.text=[[AppDeleget.statuses valueForKey:@"mlsno"] objectAtIndex:indexPath.row];
    cell.price.text=[[AppDeleget.statuses valueForKey:@"price"] objectAtIndex:indexPath.row];
    cell.address.text=[[AppDeleget.statuses valueForKey:@"address"] objectAtIndex:indexPath.row];
    cell.bedsbaths.text=bedsbaths;
    NSString *filePath = [self getImagePath];
    UIImage * img = [UIImage imageWithContentsOfFile:filePath];
    cell.myimageView.image=img;
    cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
    return cell;

}
    -(NSString *)getImagePath
    {
      /*here you can get the path of your image here*/

    }
0 голосов
/ 25 мая 2011

Пока вы сохраняете ссылку на ячейку, это не так уж сложно. Я бы сказал об этом так:

- (void)downloadDone:(UIImage*)img {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:yourCellRow inSection:yourCellSection];
    UITableViewCell *cell = [myTableView cellForRowAtIndexPath:indexPath];
    // now you have the cell you wish to modify;
    cell.myimageView.image=img;
    [myTableView reloadData];
    // if you would prefer, you could also call [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]
    // if you only want to reload that specific cell;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...