0

可能重复:
UITableView 中的延迟加载图像

我有 40 行的 tableview,我想从 URL 向每个单元格添加图像。但问题是,当我启动我的应用程序时,它会冻结一段时间,直到从各种 URL 加载所有图像?我希望图像在加载时一张一张显示,并且我的应用程序不能冻结。所以请回答我...?

4

1 回答 1

0
@interface ImageLoading : UIView {

NSURLConnection* connection;
NSMutableData* data;
NSArray *userArr1;
UIActivityIndicatorView *progress;
}

 @property (nonatomic, retain) NSArray *userArr1;

  - (void)loadImageFromURL:(NSURL*)url;

  @end

然后在实现文件中

  @implementation ImageLoading

   - (id)initWithFrame:(CGRect)frame
  {
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    }
 return self;
   }

   - (void)loadImageFromURL:(NSURL*)url {    

   progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(5, 5, 25, 25)];
progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self addSubview:progress];
[progress startAnimating];

NSURLRequest* request =[NSURLRequest requestWithURL:url];

connection = [[NSURLConnection alloc]
              initWithRequest:request delegate:self];
   }

       - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

if (data==nil) {
    data =
    [[NSMutableData alloc] initWithCapacity:2048];
}

[data appendData:incrementalData];
 }

  - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

       connection=nil;

       if ([[self subviews] count]>0) {
    [[[self subviews] objectAtIndex:0] removeFromSuperview];
       }

      UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage  imageWithData:data]];
     imageView.frame = self.bounds;
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );    

// Begin a new image that will be the new image with the rounded corners 
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);

// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                            cornerRadius:5.0] addClip];
// Draw your image
[[UIImage imageWithData:data] drawInRect:imageView.bounds];

// Get the image, here setting the UIImageView image
imageView.image = UIGraphicsGetImageFromCurrentImageContext();

// Lets forget about that we were drawing
UIGraphicsEndImageContext();

[self addSubview:imageView];
[progress stopAnimating];

[imageView setNeedsLayout];
[self setNeedsLayout];
data=nil;
  }

  - (UIImage*) image {

 UIImageView* iv = [[self subviews] objectAtIndex:0];
 return [iv image];
   }

 @end

在您的表格视图单元格中

   ImageLoading* asyncImage = [[ImageLoading alloc]
                               initWithFrame:frame];
    asyncImage.tag = 999;
    [asyncImage loadImageFromURL:url];
  [cell.contentView addSubview:asyncImage];

你可以用这个

同样的问题

于 2012-11-20T06:55:04.243 回答