user1561346
user1561346

Reputation: 502

Update UITableViewCell while scrolling

I'm trying to load images from server to cell asynchronously. But images not changing while scrolling, only after scrolling stops. "loaded" messages appear in console only after scrolling stops too. I want images appear in cell while scrolling.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = (CustomCell *)[_tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    ZTVRequest *request = [[ZTVRequest alloc] init];
    [request getSmallImg completionHandler:^(UIImage *img, NSError *error) {
        if (! error) {
            NSLog(@"loaded")
            cell.coverImgView.image = img;
        }
    }];

    return cell;
}

Upvotes: 1

Views: 826

Answers (1)

user1561346
user1561346

Reputation: 502

I'm using NSURLConnection for loading image. I found solution in this answer: https://stackoverflow.com/a/1995318/1561346 by Daniel Dickison

Here it is:

The reason the connection delegate messages aren't firing until you stop scrolling is because during scrolling, the run loop is in UITrackingRunLoopMode. By default, NSURLConnection schedules itself in NSDefaultRunLoopMode only, so you don't get any messages while scrolling.

Here's how to schedule the connection in the "common" modes, which includes UITrackingRunLoopMode:

NSURLRequest *request = ...
NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
            forMode:NSRunLoopCommonModes];
[connection start];

Note that you have to specify startImmediately:NO in the initializer, which seems to run counter to Apple's documentation that suggests you can change run loop modes even after it has started.

Upvotes: 1

Related Questions