2016-01-07 2 views
1

Мне нужно установить высоту для ячеек на основе высоты UIImageView, которая scaledHeight переменной им получать изображения с Parse, как это в моем cellForRowAtIndexPathКак установить разные высоты UITableViewCell на основе высоты UIImageView?

PFFile *userImageFile = object[@"image"]; 
    [userImageFile getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) { 
     if (!error) { 
      // UIImageView *imageView = (UIImageView *)[cell viewWithTag:1]; 
      UIImage *image = [UIImage imageWithData:data]; 
      // imageView.image = image; 


      UIImageView *test = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 400, 320)]; 
      test.image = image; 

      CGSize imgSize = image.size; 
      CGFloat ratio = test.frame.size.width/imgSize.width; 
      CGFloat scaledHeight = imgSize.height * ratio; 

      [test setFrame:CGRectMake(0, 0, self.view.window.frame.size.width, scaledHeight)]; 

      NSLog(@"HEIGHT:%f",scaledHeight); 

      [cell addSubview:test]; 

     } 
    } progressBlock:^(int percentDone) 
    { 

    }]; 

как я могу установить scaledHeight внутри heightForRowAtIndexPath в heightForRowAtIndexPath является запустить до CellForRowAtIndexPath?

ответ

1
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //This is for same height of image view 
    uitableViewCell *cell = [tableView cellforRowAtIndexPath : indexPath]; 
    return cell.imageView.size.height; 
    //If you have different sizes of images then store all those image in array and then calculate the height. 

} 
+0

как бы вычислить высоту изображения внутри 'heightForRow..' – farhan

+0

imageView.size.height даст вам высоту. –

+0

Как бы это сделать, если изображениеView установлено в cellForRow? – farhan

1

1. Попытка установить высоту по умолчанию в массиве

- (void)setDefaultRowHeights { 
    self.imageHeights = [NSMutableArray arrayWithCapacity:self.imageURLs.count]; 
    for (int i = 0; i < self.imageURLs.count; i++) { 
     self.imageHeights[i] = @(self.tableView.rowHeight); 
    } 
} 

2. В cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    NSString *imageURL = self.imageURLs[indexPath.row]; 
    __weak TableViewCell *weakCell = cell; 
    __weak typeof(self) weakSelf = self; 
    [cell.mainImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]] 
           placeholderImage:[UIImage new] 
             success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 
              weakCell.mainImageView.image = image; 

              // Calculate Heights 
              NSInteger oldHeight = [weakSelf.imageHeights[indexPath.row] integerValue]; 
              NSInteger newHeight = (int)image.size.height; 

              // Update table row height if image is in different size 
              if (oldHeight != newHeight) { 
               weakSelf.imageHeights[indexPath.row] = @(newHeight); 
               [weakSelf.tableView beginUpdates]; 
               [weakSelf.tableView endUpdates]; 
              } 
             } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { 
              NSLog(@"Error:"); 
             }]; 

    return cell; 
} 

3. В heightForRowAtIndexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
     return [self.imageHeights[indexPath.row] integerValue]; 
    } 
+0

does not это не работает, потому что heightForRowAtIndexPath загружается до CellforRowAtIndexPath, im загрузка изображений в cellForRowAtIndexPath – farhan

+0

Пожалуйста, проверьте отредактированный ответ – darshan

1

Поскольку вы по умолчанию загружаете изображение по асинхронно, вам необходимо вернуть некоторое значение по умолчанию в метод heightForRowAtIndexPath. После загрузки изображения вам нужно перезагрузить только эту определенную строку. Теперь снова вызывается heightForRowAtIndexPath, где вы возвращаете фактическую высоту изображения. Вы также можете добавить некоторую анимацию при перезагрузке определенной строки, чтобы переход на UI был плавным.

+0

пример о том, как это сделать? – farhan

+0

tableView.reloadRowsAtIndexPaths ([NSIndexPath.init (forItem: 0, inSection: 0)], withRowAnimation: .Automatic) –

0

Получить размер изображения с учетом высоты и вернуть его на heightForRowAtIndexPath. Это будет динамически отличаться вашей высотой в соответствии с размером вашей высоты изображения.

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //Assign your url 
    NSURL* aURL = [NSURL URLWithString:@"URL"]; 

    //get data of that url image. 
    NSData* data = [[NSData alloc] initWithContentsOfURL:aURL]; 

    //get image 
    UIImage *image = [UIImage imageWithData:data]; 

    //return it's bounding height (bounds return the area of height image requires.) 
    return image.bounds.height; 
} 
0

Возьмите одну mutablearray (NSMutableArray *arrayHeights) по умолчанию этот массив имеет количество объектов, равное общему количеству строк. и все они установили значение «0»

и heightForRowAtIndexPath возвращение

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return [arrayHeights[indexPath.row] floatValue] + 50.0; // 50 is default space set it according your requirements 
} 

теперь, когда вы получаете в результате getDataInBackgroundWithBlock заменить объект arrayHeights с высоты изображения для данного индекса и перезагрузить эту ячейку

PFFile *userImageFile = object[@"image"]; 
    [userImageFile getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) { 
     if (!error) { 
      // UIImageView *imageView = (UIImageView *)[cell viewWithTag:1]; 
      UIImage *image = [UIImage imageWithData:data]; 
      // imageView.image = image; 


      UIImageView *test = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 400, 320)]; 
      test.image = image; 

      CGSize imgSize = image.size; 
      CGFloat ratio = test.frame.size.width/imgSize.width; 
      CGFloat scaledHeight = imgSize.height * ratio; 
      [arrContactList replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithFloat:scaledHeight]]; 
      [test setFrame:CGRectMake(0, 0, self.view.window.frame.size.width, scaledHeight)]; 

      NSLog(@"HEIGHT:%f",scaledHeight); 

      [cell addSubview:test]; 
// reload cell 
     } 
    } progressBlock:^(int percentDone) 
    { 

    }]; 
Смежные вопросы