xcode iphone - отрывистая прокрутка UITableView CellForRowAtIndexPath - PullRequest
2 голосов
/ 11 августа 2010

Почти отсортировано с моим первым приложением, просто с новостным приложением, но когда я загружаю его на свой iPhone, свиток кажется отрывистым, может кто-то взглянет на мою функцию и посмотрит, что я делаю что-то не так.

Мне нужно изображение справа, поэтому я использую пользовательские ячейки.

Спасибо За любую помощь

    #define DATELABEL_TAG 1 #define MAINLABEL_TAG 2 #define PHOTO_TAG 3


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

{

static NSString *MainNewsCellIdentifier = @"MainNewsCellIdentifier";


UILabel *mainLabel, *dateLabel;

UIImageView *photo;


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier];


    if (cell == nil) 

{

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease];

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;


dateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,15.0,170.0,15.0)] autorelease];

dateLabel.tag = DATELABEL_TAG;

dateLabel.font = [UIFont systemFontOfSize:10.0];

dateLabel.textAlignment = UITextAlignmentLeft;

dateLabel.textColor = [UIColor darkGrayColor];

dateLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; //| UIViewAutoresizingFlexibleHeight;

[cell.contentView addSubview:dateLabel]; 


mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,28.0,170.0,60.0)] autorelease];

mainLabel.tag = MAINLABEL_TAG;

mainLabel.font = [UIFont boldSystemFontOfSize:14.0];

mainLabel.textColor = [UIColor blackColor];

mainLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;

mainLabel.numberOfLines = 0;

//mainLabel.backgroundColor = [UIColor greenColor];

[cell.contentView addSubview:mainLabel];


photo = [[[UIImageView alloc] initWithFrame:CGRectMake(190.0,15.0,85.0,85.0)] autorelease]; 

photo.tag = PHOTO_TAG; 

photo.contentMode = UIViewContentModeScaleAspectFit;//UIViewContentModeScaleAspectFit; //


[cell.contentView addSubview:photo];


    }

else {


dateLabel = (UILabel *)[cell.contentView viewWithTag:DATELABEL_TAG];

mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];

photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];

}


NSUInteger row = [indexPath row];

NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row];

NSString *title = [stream valueForKey:@"title"];



NSString *titleString = @"";


if( ! [title isKindOfClass:[NSString class]] )

{

titleString  = @"";

}

else 

{

titleString = title;

}


CGSize maximumSize = CGSizeMake(180, 9999);


    UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14];

    CGSize dateStringSize = [titleString sizeWithFont:dateFont 

constrainedToSize:maximumSize 

lineBreakMode:mainLabel.lineBreakMode];


    CGRect dateFrame = CGRectMake(15.0, 28.0, 170.0, dateStringSize.height);

    mainLabel.frame = dateFrame;


mainLabel.text = titleString;

dateLabel.text = [stream valueForKey:@"created"];


NSString *i = [NSString stringWithFormat:@"http://www.website.co.uk/images/%@", [stream valueForKey:@"image"]];

NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]];

UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];


photo.image = newsImage; 

[imageURL release];

[newsImage release];


    return cell;

}

Ответы [ 2 ]

0 голосов
/ 16 февраля 2013

Даже если вы загружаете изображения асинхронно, прокрутка по-прежнему будет прерывистой.

Почему?Это ленивая декомпрессия изображения.ios выполняет декомпрессию в тот момент, когда она будет отображаться на экране.Вы должны вручную распаковать изображения в фоновом потоке.

Распаковка означает не просто создание экземпляра объекта UIImage.Это может быть несколько сложно.Лучшее решение - скачать SDWebImage и использовать распаковщик изображений, который входит в комплект.SDWebImage будет асинхронно загружать и выполнять распаковку для вас.

Подробнее о проблеме см .: http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/

0 голосов
/ 11 августа 2010

Проблема в следующем:

NSString *i = [NSString stringWithFormat:@"http://www.website.co.uk/images/%@", [stream valueForKey:@"image"]];

NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]];

UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];

Здесь вы фактически говорите, что, как только ячейка должна быть отображена, изображение должно быть выбрано и представлено.Это будет стоить некоторого времени - слишком много для хорошего пользовательского опыта.

Вы должны получить изображения до или во время представления табличного представления и кэшировать их, например, в массиве.Или вы должны обрабатывать вещи асинхронно, что означает, что вы выполняете загрузку в фоновом режиме, а не ждете с return cell;, пока изображение действительно не загрузится.Это будет немного сложнее получить право.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...