我有一个UITableView,它有很多行,每行只有一个图像。为了防止延迟,我在下面使用了代码。但是现在,在Im滚动时,它会显示前几行的照片,然后对其进行校正。如何解决这个问题?

- (void)loadImageNamed:(NSString *)name {
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        // Determine path to image depending on scale of device's screen,
        // fallback to 1x if 2x is not available
        NSString *pathTo1xImage = [[NSBundle mainBundle] pathForResource:name ofType:@"jpg"];

        NSString *pathToImage = pathTo1xImage;

        UIImage *uiImage = nil;

        if (pathToImage) {
            // Load the image
            CGDataProviderRef imageDataProvider = CGDataProviderCreateWithFilename([pathToImage fileSystemRepresentation]);
            CGImageRef image = CGImageCreateWithJPEGDataProvider(imageDataProvider, NULL, NO, kCGRenderingIntentDefault);


            // Create a bitmap context from the image's specifications
            // (Note: We need to specify kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little
            // because PNGs are optimized by Xcode this way.)
            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetWidth(image) * 4, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);


            // Draw the image into the bitmap context
            CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image);

            //  Extract the decompressed image
            CGImageRef decompressedImage = CGBitmapContextCreateImage(bitmapContext);


            // Create a UIImage
            uiImage = [[UIImage alloc] initWithCGImage:decompressedImage];


            // Release everything
            CGImageRelease(decompressedImage);
            CGContextRelease(bitmapContext);
            CGColorSpaceRelease(colorSpace);
            CGImageRelease(image);
            CGDataProviderRelease(imageDataProvider);
        }


        // Configure the UI with pre-decompressed UIImage
        dispatch_async(dispatch_get_main_queue(), ^{
            self.categoryImageLabel.image = uiImage;
        });
    });
}

最佳答案

其他答案告诉您该怎么做,但不告诉您原因。

像一个单元格一样,您必须在医生办公室的候诊室中填写表格。想象一下,办公室将重复使用这些表格,并且每个患者在填写其信息之前都必须擦除表格上的所有数据。

如果您没有任何过敏,可能会诱使您跳过过敏部分,因为它们不适用于您。但是,如果最后一个人过敏,而您没有删除他们的答案,他们的答案仍会显示在表格上。

同样,当您使回收单元出队时,您必须清除所有字段,即使是不适用于您的字段。您应该将图像设置为nil或它们的起始占位符值。

请注意,如果您异步加载数据,则仍应首先将字段重置为其默认值,因为在异步加载完成之前,旧值会一直显示。这就是您的情况。

您可以在cellForRowIndexPathprepareForReuse中将图像设置为nil / placeholder,但是需要在其中一个位置将其重置,否则您将看到剩余的图像,直到新的图像完成加载为止。

10-07 19:39
查看更多