我正在尝试使用进度条加载更新每个表格单元格,但我被卡住了.
我为具有以下属性的表视图创建了一个自定义单元格:
我为具有以下属性的表视图创建了一个自定义单元格:
@interface OFPTableCell : UITableViewCell @property (nonatomic,weak) IBOutlet UILabel *textLabel; @property (nonatomic,weak) IBOutlet UILabel *detailTextLabel; @property (weak,nonatomic) IBOutlet UIImageView *imageView; @property (weak,nonatomic) IBOutlet UIProgressView *progressView; @end;
在@synthesize它们之后,现在我在每个表格单元格中都有预期的进度条.
问题是,当我尝试使用加载进度条更新甚至第一个单元格时,它只是不执行任何操作或设置为0或完整进度条.
请注意,下载过程正常.
您可以找到我尝试更新进度条的代码:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite: (int64_t)totalBytesExpectedToWrite { dispatch_async(dispatch_get_main_queue(),^{ NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; OFPTableCell *cell = (OFPTableCell*)[self tableView:self.tableViewCache cellForRowAtIndexPath:indexPath]; cell.progressView.progress=(double)totalBytesWritten / (double)totalBytesExpectedToWrite; }); }
下面是方法cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { OFPTableCell *cell = [self.tableViewCache dequeueReusableCellWithIdentifier:@"Cell"]; OFPVideoDetails *vd = [someArray objectAtIndex:indexPath.row]; cell.textLabel.text=vd1; cell.detailTextLabel.text=vd2; CGSize size = {65,53}; cell.imageView.image =[self imageWithImage:[UIImage imageWithContentsOfFile:vd.imageUrl] scaledToSize:size]; cell.delegate = self; return cell; }
解决方法
调用方法tableView:cellForRowAtIndexPath:是非常糟糕的做法,因为单元格可能不存在于同一时刻,它可能是你所拥有的bug的原因.
基本上你应该用另一种方式做到这一点:添加一个double数组:
double progressValues[30]; // 30 is the count of rows on your tableView,you can set the size dynamically
并像这样使用它:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite: (int64_t)totalBytesExpectedToWrite { dispatch_async(dispatch_get_main_queue(),^{ NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; OFPTableCell *cell = (OFPTableCell*)[self tableView:self.tableViewCache cellForRowAtIndexPath:indexPath]; progressValues[indexPath.row] = (double)totalBytesWritten / (double)totalBytesExpectedToWrite; [self.tableViewCache reloadData]; }); }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //... your code... cell.progressView.progress = progressValues[indexPath.row]; // ... return cell; }