2015-10-28 5 views
0

У меня так UITableView, что у меня есть пользовательская ячейка. Эта пользовательская ячейка содержит некоторые ярлыки. Текст ярлыка может быть динамическим в зависимости от Json. Теперь я хочу сделать высоту ячейки на основе высоты содержимого метки, поэтому я использовал метод heightForRowAtINdexPath. Теперь я получаю эту ячейку.Увеличьте высоту ячейки без ее настройки?

if(!self.customCell) 
    { 
     self.customCell = [self.table_view dequeueReusableCellWithIdentifier:@"homeCell"]; 
    } 

метки могут быть многострочный в зависимости от data.So я, если написать один и тот же код cellForRowAtiNdexPath в heightForRowAtIndexPath тогда я получить больше height.but, если я не пишу один и тот же код, то я получаю меньше высоты для этикетки. на данный момент я написал ниже код для heightForRowAtIndexPath.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGFloat height; 
     float like_height,c_one_height,c_two_height,c_three_height,tv_height,header_height,operations_height,img_like_icon_height,img_comment_icon_height,header_margin=5,tv_container_margin=5,operations_margin=5,like_top_margin=11,first_comment=10,second_comment=5,third_comment=5; 
    //define variables here 
    if(!self.customCell) 
    { 
     self.customCell = [self.table_view dequeueReusableCellWithIdentifier:@"homeCell"]; 
    } 
    Post *user_post=[arr_post objectAtIndex:indexPath.row]; 
    int like_count=[user_post.like_count intValue]; 
    float comment_count=[user_post.comment_count intValue]; 
    if (self.customCell.beizer_image != nil) 

    { 
     NSLog(@"inside cell beizer"); 

     [self.customCell.beizer_image removeFromSuperview]; 

     self.customCell.beizer_image=nil; 

     self.customCell.tv_post.textContainer.exclusionPaths=NULL; 

     self.customCell.beizer_path=nil; 

    } 
    [self.customCell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
    self.customCell.tv_post.text=user_post.post_description; 
    self.customCell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]]; 
    [self.customCell.tv_post setTextColor:[self colorFromHexString:user_post.font_color]]; 
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"]) 
    { 

     NSLog(@"NOT INSIDE THE CONDITION"); 

    } 
    else 
    { 
     NSLog(@"INSIDE BEIZER PATH CONDITION"); 
     self.customCell.beizer_path = [UIBezierPath bezierPathWithRect:CGRectMake(5, 5, 100, 100)]; 
     self.customCell.tv_post.textContainer.exclusionPaths = @[self.customCell.beizer_path]; 
     self.customCell.beizer_image =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 100, 100)]; 

     if(![user_post.post_image isEqualToString:@"none"]) 
     { 
      [self.customCell.beizer_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_image]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]]; 

     } 
     if(![user_post.post_video isEqualToString:@"none"]) 
     { 
      [self.customCell.beizer_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]]; 

     } 
     [self.customCell.tv_post addSubview:self.customCell.beizer_image]; 
    } 
    //make textview height dynamic 
    self.customCell.tv_post.scrollEnabled=NO; 
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"]) 
    { 
     CGFloat fixedWidth = self.customCell.tv_post.frame.size.width; 
     CGSize newSize = [self.customCell.tv_post sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; 
     CGRect newFrame = self.customCell.tv_post.frame; 
     newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); 
     self.customCell.tv_post.frame = newFrame; 
     self.customCell.tv_height.constant=self.customCell.tv_post.frame.size.height; 
     [self.customCell.view_tvContainer layoutIfNeeded]; 
    } 
    else 
    { 
     CGFloat fixedWidth = self.customCell.tv_post.frame.size.width; 
     CGSize newSize = [self.customCell.tv_post sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; 
     CGRect newFrame = self.customCell.tv_post.frame; 
     newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth),fmax(self.customCell.beizer_image.frame.size.height+10,newSize.height)); 
     self.customCell.tv_post.frame = newFrame; 
     self.customCell.tv_height.constant=self.customCell.tv_post.frame.size.height; 
     [self.customCell.view_tvContainer layoutIfNeeded]; 
    } 

// self.customCell.f_comment_top.constant=-2100; 
// [self.customCell layoutIfNeeded]; 
    if(like_count>0) 
    { 
     like_height=self.customCell.label_like_count.frame.size.height; 
    } 
    else 
    { 
     like_height=0; 
     img_like_icon_height=0; 
    } 
    if(comment_count<=0) 
    { 
     c_one_height=0; 
     c_two_height=0; 
     c_three_height=0; 
     img_comment_icon_height=0; 
    } 
    else if(comment_count==1) 
    { 

     if(like_count<=0) 
     { 
      self.view.translatesAutoresizingMaskIntoConstraints = NO; 
      self.customCell.f_comment_top.constant=-21; 
      [self.customCell layoutIfNeeded]; 
     } 
     c_one_height=self.customCell.first_comment.frame.size.height; 
     c_two_height=0; 
     c_three_height=0; 

    } 
    else if(comment_count==2) 
    { 
     if(like_count<=0) 
     { 
      self.view.translatesAutoresizingMaskIntoConstraints = NO; 
      self.customCell.f_comment_top.constant=-21; 
      [self.customCell layoutIfNeeded]; 
     } 
     c_one_height=self.customCell.first_comment.frame.size.height; 
     c_two_height=self.customCell.second_cmment.frame.size.height+15; 
     c_three_height=0; 
    } 
    else if(comment_count==3) 
    { 
     if(like_count<=0) 
     { 
//   self.customCell.f_comment_top.constant=1020; 
//   [self.customCell.first_comment layoutIfNeeded]; 
     } 
     else 
     { 

     } 
     c_one_height=self.customCell.first_comment.frame.size.height; 
     c_two_height=self.customCell.second_cmment.frame.size.height; 
     c_three_height=self.customCell.third_comment.frame.size.height+15; 
    } 
    tv_height=self.customCell.view_tvContainer.frame.size.height; 
    header_height=self.customCell.header_view_height.frame.size.height; 
    operations_height=self.customCell.view_operations_height.frame.size.height; 
    height = like_height+c_one_height+c_two_height+c_three_height+tv_height+operations_height+header_height; 
    CGFloat margin_height=header_margin+operations_margin+tv_container_margin+like_top_margin+first_comment+second_comment+third_comment+img_comment_icon_height+img_like_icon_height; 
    NSLog(@"like label height is %f",like_height); 
    NSLog(@"first comment height is %f",c_one_height); 
    NSLog(@"second comment height is %f",c_two_height); 
    NSLog(@"third comment height is %f",c_three_height); 
    NSLog(@"all margin height is %f",margin_height); 
    NSLog(@"height is %f",height); 

    // Padding of 1 point (cell separator) 
    height=height+margin_height; 
    CGFloat separatorHeight = 1; 
    return height; 

} 

Я видел много примеров, в которых написано, что для настраиваемой ячейки код cellForRowAtIndexPath записывается в heightForRowAtIndexPath.

  1. Почему я должен повторять код cellForRowAtIndexPath в heightForRowAtIndexPath?

ответ

0

Почему мне нужно повторить код для cellForRowAtIndexPath в heightForRowAtIndexPath?

потому что heightForRowAtIndexPath всегда дозвонились до того cellForRowAtIndexPath. Таким образом, чтобы вычислить высоту в heightForRowAtIndexPath, вы создали эту ячейку в heightForRowAtIndexPath.

Лучший способ использовать autolayout для расчета динамической высоты: - Вы можете обратиться следующие Link сделать то же самое.

+0

Это будет процесс занимает много времени, а это снижает производительность. – Techiee

+0

нет .... автоспуск будет работать как шарм ..... вы должны попробовать, если знаете, как использовать автозапуск. – KavyaKavita

1

Нет необходимости настраивать ячейку entire, которую вы указали в cellForRowAtIndexPath, в heightForRowAtIndexPath.

Это два метода, используемые для конкретной функциональности.

cellForRowAtIndexPath - это метод DataSource, который предназначен для настройки вашей ячейки в tableview.

heightForRowAtIndexPath является Delegate метод, который предназначен для вычисления высоты tableviewcell или row на основе контента, который вы собираетесь показывать в cellForRowAtIndexPath.

Например, если вы настраиваете клетки с UILabel (не важно, сколько этикетки) и присвоить метку с текстом в cellForRowAtIndexPath, то в heightForRowAtIndexPath, принеси текст, который вы назначили на этикетке, высота calcluate лейбла и дать эту высоту метки ячейке. Это создаст ячейку с высотой в соответствии с высотой вашего ярлыка.

Например, в вашем cellForRowAtIndexPath,

 .....//your cell configuration code above//..... 
     UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero]; 
     [lbl_myText setLineBreakMode:NSLineBreakByWordWrapping]; 
     lbl_myText.minimumScaleFactor = FONT_SIZE; 
     [lbl_myText setNumberOfLines:0]; 
     lbl_myText.textAlignment = NSTextAlignmentRight; 
     [lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

     NSString *text = [arr_text objectAtIndex:indexPath.row]; 
     CGSize constraint = CGSizeMake(Your_MAX_LabelWidth, Your_MAX_LabelHeight); 


     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 

     paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; 


     CGRect textRect = [text boundingRectWithSize:constraint 
               options:NSStringDrawingUsesLineFragmentOrigin 
               attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy} 
               context:nil]; 

     size = textRect.size; 


     [lbl_myText setText:text]; 
     float widthIs = [lbl_myText.text 
      boundingRectWithSize:constraint 
      options:NSStringDrawingUsesLineFragmentOrigin 
      attributes:@{ NSFontAttributeName:lbl_myText.font } 
      context:nil] 
      .size.width; 
     [lbl_myText setFrame:CGRectMake(X_co,Y_co,widthIs,size.height)]; 

в heightForRowAtIndexPath:

.....//NO cell configuration code above//..... 
    NSString *cellText = [arr_text objectAtIndex:indexPath.row]; 

    CGSize constraint = CGSizeMake(Your_MAX_LabelWidth, Your_MAX_LabelHeight); 

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 

    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; 

    ////for message label 
    CGRect textRect = [cellText boundingRectWithSize:constraint 
              options:NSStringDrawingUsesLineFragmentOrigin 
              attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy} 
              context:nil]; 

    CGSize labelsize = textRect.size; 



    ///calculate Cell the height 
    CGFloat height = MAX(labelsize.height, your_defaultcell_height); 

    if(height == your_defaultcell_height) 
    { 
     return your_defaultcell_height + 10; //10 is buffer height 
    } 

    else 
    { 
     return height + 10; //10 is buffer height 
    } 
Смежные вопросы