0

重複の可能性:
UITableView での画像の遅延読み込み

40行のテーブルビューがあり、URLから各セルに画像を追加したい. しかし、問題は、アプリを起動すると、さまざまな URL からすべての画像が読み込まれるまで、しばらくの間フリーズすることですか? 画像が読み込まれるときに画像を 1 つずつ表示したいのですが、アプリがフリーズしてはいけません。では、答えてください...?

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 に答える