tableview中的单元格不能平滑滚动

时间:2014-02-15 06:18:01

标签: ios iphone objective-c ios7

我差不多已经完成了我的应用程序编码,但我仍然有一个问题,我几周都无法解决...我浏览了这个网站和其他网站上同一个问题,但我找不到办法解决这个问题。 我有一个带有单元格(如Instagram)的表视图,其中包含从服务器下载的图像。我的问题是当我滚动表格视图时,它不平滑而且闪烁。

要构建表视图,我执行以下操作:

- 标题视图和单元格是子类。 - 我下载所有图像异步,然后在我的应用程序的tmp文件夹中缓存它们(每个约25Ko)。 - 下载的每个图像与应放置它的UIImageView具有相同的帧。 - 我试图以png和jpeg格式保存图像,但问题仍然存在。

我做了另一个测试,而不是将下载的图像放在单元格中,我在我的应用程序中放置了一个图像(任何缩放)。在这种情况下,表格视图平滑滚动。

所以我怀疑问题可能是我缓存图像并从缓存中获取它们的方式。但即便在这种情况下,我尝试使用NSCache和临时文件夹缓存图像,但没有结果......

这是我的代码:

-(void)CacheTheImageDownloaded: (NSData *)TheImageData : (NSString*)PathOfImage{

   NSFileHandle *fout;
   [[NSFileManager defaultManager] createFileAtPath:PathOfImage contents:Nil   attributes:Nil];
   fout = [NSFileHandle fileHandleForWritingAtPath:PathOfImage];
   [fout writeData:TheImageData ];
   [fout closeFile];

}


-(UIImage*)GetTheImageFromTemporaryDirectory:(NSString*)ImagePath{
   UIImage *theCachedImage;
   theCachedImage = [UIImage imageWithContentsOfFile:ImagePath];
   return theCachedImage;
}


-(void)GetImageForTheViewedCell: (NSString*) ImageName : (NSString*)TheImageURL :    (NSInteger)therow : (UIImageView*)MyImageView {

  NSString *TheKey = [NSString stringWithFormat:@"%ld", (long)therow];
  NSString *tmpDir = NSTemporaryDirectory();
  NSString *ImageDownloadedTmpDir;
  ImageDownloadedTmpDir = [tmpDir stringByAppendingPathComponent:@"TMPImagesDownloaded"];

  NSMutableString *TheImagePath = [NSMutableString stringWithString:ImageDownloadedTmpDir];
  [TheImagePath appendString:@"/"];
  [TheImagePath appendString:ImageName ];

if ( [self VerifyIfImageIsAlreadyCached:TheImagePath]){
    MyImageView.image = [self GetTheImageFromTemporaryDirectory:TheImagePath];
}
else{
    NSBlockOperation *loadImageIntoCellOp = [[NSBlockOperation alloc] init];
    [loadImageIntoCellOp addExecutionBlock:^(void){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),  ^{
            NSURL *theURL = [NSURL URLWithString:TheImageURL];
            NSData *data1 = [NSData dataWithContentsOfURL:theURL ];
            NSData *data = UIImagePNGRepresentation([UIImage imageWithData:data1]);
            dispatch_sync(dispatch_get_main_queue(), ^{
                MyImageView.image = [UIImage imageWithData:data];
                NSBlockOperation *ongoingDownloadOperation =       [self.TheImageDownloadOperations objectForKey:TheKey];
                if (ongoingDownloadOperation) {
                    [self.TheImageDownloadOperations removeObjectForKey:TheKey];
                }
                [self CacheTheImageDownloaded:data :TheImagePath];
            });
        });
    }];

    if (TheKey) {
        [self.TheImageDownloadOperations setObject:loadImageIntoCellOp forKey:TheKey];
    }

    if (loadImageIntoCellOp) {
        [self.imageLoadingOperationQueue addOperation:loadImageIntoCellOp];
    }

}


}

我正在研究Xcode 5.02。

感谢您的建议!

修改

这是我的CellForRowAtIndexpath代码:

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


 static NSString *cellIdentifier = @"myCustomCell";
 MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
 if (cell == nil){
     cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
 }
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

NSInteger row = indexPath.row;
cell.tag = row ;

//The Profile picture
NSString *theurl = self.myProfilePics[row];
NSString *TheImageName = self.TheImageNames[row];
[self GetImageForTheViewedCell:TheImageName:theurl:row: cell.ProfilePicView];  //getting image from the cache or downloaded async
[cell.TheProfilePicButton setBackgroundImage:cell.ProfilePicView.image forState:UIControlStateNormal];
[cell.contentView addSubview: cell.TheProfilePicButton];

//Username:
NSString *myusername = self.Usernames[row];
[cell.UsernameButton setTitle: myusername forState:UIControlStateNormal];
[cell.contentView addSubview:cell.UsernameButton];

//date
NSString *mydate =  self.Dates[row];
[cell.DateLabel setText: mydate];
[cell.contentView addSubview: cell.DateLabel];

return cell;

}

1 个答案:

答案 0 :(得分:0)

你说'我试图用png和jpeg格式保存图像'。我想,你只是“保存以缓存”图像。您在tableview中使用UIImagePNGRepresentation

即使您实施“延迟加载”,当您加载许多图像时,UITableView的性能也会非常低。

所以,我的回答是您应该使用UIImageJPEGRepresentation代替UIImagePNGRepresentation

修改

如何使用UIGraphicsGetImageFromCurrentImageContext

UIImage *image = [UIImage imageWithContentsOfFile:filePath];
CGSize imageSize = image.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
[image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

还有一个,NSCache如何改善表现。这是一个样本

@inteface YourTableViewController ()
@property (nonatomic) NSCache *cache;
@end

@implemetation YourTableViewController

.
.
.

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

    if (cell == nil)
    {
        cell = [[YourCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.yourImageView.frame = CGRectMake((self.frame.size.width - self.rowHeight)*0.5f, 0, self.rowHeight, self.rowHeight);
    }
    [cell.imageView setImage:nil];
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(globalQueue, ^(){

        UIImage *image = [self.cache objectForKey:filePath];
        if (image == nil) {
            image = [UIImage imageWithContentsOfFile:filePath];
            CGSize imageSize = image.size;
            UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
            [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            [self.cache setObject:image forKey:filePath];
        }

        dispatch_async(mainQueue, ^(){
            if ([[tableView indexPathsForVisibleRows] containsObject:indexPath]) {
                YourCell *cell = (YourCell *)[tableView cellForRowAtIndexPath:indexPath];
                if(image) {
                    [cell.yourImageView setImage:image];
                }
            }
        });
    });
    return cell;
}

.
.
.

@end