2014-10-06 74 views
4

我有一個應用程序,其中我有一個表格,並在該tableview的每一行我動態創建一個自定義tableview單元格。根據自定義單元格增加主桌面行高度

下面是該代碼。

NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"flowviewTableViewCell" owner:self options:nil]; 

cell2 = [nib objectAtIndex:0]; 

return cell2; 

「FlowTableViewCell」是一個UITableViewCell。 在這個自定義單元格中,我有一個tableview。

我顯示了一些數據在我的自定義tableview單元格從一個數組和這些數據的長度不同。它不是固定的。

根據自定義tableview單元的大小,我可以增加自定義單元大小,但不能增加主要的tableview行高度。

我想根據自定義tableview單元的大小動態增加主tableview的單元大小的高度。

使用以下代碼,自定義tableView單元格的高度正在增加。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    NSString *str = [arrComments objectAtIndex:indexPath.row]; 
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping]; 
    NSLog(@"%f",size.height); 
    if (size.height<20) 

    { 
     size.height=20; 
     //m= size.height; 

    } 

    NSLog(@"%f",size.height); 

    return size.height + 30; 


} 

如何根據自定義tableviewcell的大小調整主桌面視圖行高的高度?

在這裏,我附上了一些截圖,以便更好地理解。

以下是我的自定義TableViewCell:

Custom TableViewCell

以下是我的主要的TableView:

Main TableView

以下是現在我得到的輸出:

output getting right now

您可以在上圖中看到,comment2被剪切,並且同一帖子的comment3被顯示在下一篇文章中。

我想要像下面的圖像輸出。

enter image description here

所以,我的問題是如何提高的主要的tableview的單元尺寸的高度動態地根據自定義的tableview單元格的大小?

請幫幫我。任何幫助將不勝感激

回答

3

您可以使用下面的代碼來動態地調整高度非常簡單solution。首先,您需要確定標籤的高度,然後相應地調整單元格的高度。我一直在我的聊天應用程序中使用此代碼,並正常工作。

首先,在cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
      /// Set Text Label 

      UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero]; 
      [lbl_myText setLineBreakMode:NSLineBreakByWordWrapping]; 
      lbl_myText.minimumScaleFactor = FONT_SIZE; 
      [lbl_myText setNumberOfLines:0]; 
      lbl_myText.textAlignment = NSTextAlignmentLeft; 
      [lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

      NSString *text = [arr_text objectAtIndex:indexPath.row]; 

      CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

      // Checks if text is multi-line 
      if (size.width > lbl_myText.bounds.size.width) 
      { 
       CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); //// Here Width = Width you want to define for the label in its frame. The height of the label will be adjusted according to this. 

       //CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 

       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]; 

       CGSize size = textRect.size; 

       [lbl_myText setText:text]; 
       [lbl_myText setFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_someoneImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))]; 
      } 

      else 
      { 
       lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 18,18); 
       lbl_myText.textAlignment = NSTextAlignmentLeft; 
       [lbl_myText setText:text]; 
      } 

      //lbl_myText.backgroundColor = [UIColor greenColor]; 

      [cell.contentView addSubview:lbl_myText]; 

      /// Set Date Label 

      NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
      [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; 
      NSString *stringFromDate = [formatter stringFromDate:[arr_date objectAtIndex:indexPath.row]]; 

      UILabel *lbl_myDate = [[UILabel alloc]initWithFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, lbl_myText.frame.size.height+10, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 10 ,18)]; 
      lbl_myDate.text = stringFromDate; 
      lbl_myDate.font = [UIFont fontWithName:@"Helvetica Neue" size:13.0]; 
      lbl_myDate.textColor = [UIColor lightGrayColor]; 
      lbl_myDate.textAlignment = NSTextAlignmentLeft; 
      [cell.contentView addSubview:lbl_myDate]; 

      /// Set User Image 

      UIImageView *imgv_myImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, lbl_myText.frame.origin.y, 63, 63)]; 
      imgv_myImage.image = selectedUserUploadedImage; 

      [cell.contentView addSubview:imgv_myImage]; 
} 

這裏的標籤和圖像視圖定義一些常量:

#define FONT_SIZE 15.0f 
#define CELL_CONTENT_WIDTH 320.0f /// change this according to your screen size. This is just an example 
#define CELL_CONTENT_MARGIN 10.0f 

現在,創建標籤後,你將不得不決定高度細胞在heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellText = [arr_text objectAtIndex:indexPath.row]; 

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; 
    NSString *cellDate = [formatter stringFromDate:[arr_date objectAtIndex:indexPath.row]]; 

    // NSString *text = [items objectAtIndex:[indexPath row]]; 

    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); 

    //CGSize labelsize = [cellText sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 

    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; 

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

    CGSize datelabelsize = datetextRect.size; 


    //CGSize datelabelsize = [cellDate sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 

    ///combine the height 
    CGFloat height = MAX(labelsize.height + datelabelsize.height, 64.0f); 

    if(height == 64.0f) 
    { 
     return 74; /// label is of one line, return original/ static height of the cell 
    } 

    else 
    { 
     return height + 10; /// label is of multi-line, return calculated height of the cell + some buffer height 
    } 

} 
5

可以使用計算標籤的高度:

- (CGRect)heightOfLabel:(UILabel*)resizableLable 
{ 
    CGSize constrainedSize = CGSizeMake(resizableLable.frame.size.width , 9999); 

     NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
               [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName, 
               nil]; 

     NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary]; 

     CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil 

     ]; 


     if (requiredHeight.size.width > self.resizableLable.frame.size.width) { 
      requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height); 
     } 

     return requiredHeight; 
    } 

調用此方法從TableView中的委託方法:

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath { 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    return [self heightOfLabel:cell.textLabel]; 

} 
+0

在哪個方法我應該寫這個&我應該返回什麼? – 2014-10-06 06:24:07

+0

這兩種方法都必須插入到你的UITableViewController類中。第一個是計算CGRect的常規方法,第二個是UITableViewDelegate的一個方法 – 2014-10-06 08:51:28

+0

它給了我一個錯誤'返回'CGRect'(又名'struct CGRect')與一個函數不兼容的結果類型'CGFloat'(又名'浮動「)'。 – 2014-10-06 09:29:25

0
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

NSString *str = [arrComments objectAtIndex:indexPath.row]; 
UIFont *font = [UIFont fontWithName:@"Helvetica" size:14]; 
CGRect new = [str boundingRectWithSize:CGSizeMake(280, 999) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: font} context:nil]; 
CGSize size= new.size; 
NSLog(@"%f",size.height); 
if (size.height<20) 

{ 
    size.height=20; 
    //m= size.height; 

} 

NSLog(@"%f",size.height); 

return size.height + 30; 


} 
+0

我已經試過,但沒有工作。 – 2014-10-06 12:30:29

+0

如果行中有兩個標籤,則必須添加兩個標籤高度並檢查您是否獲得正確的字符串值NSString * str = [arrComments objectAtIndex:indexPath.row];通過放置NSLog和檢查size.height NSLog – 2014-10-06 13:16:54

+0

該'str'值ok,@MaulikShah – 2014-10-07 06:03:10

0

這裏,我們去:

  1. 創建一個共同的UITableViewCell子類,用於視圖中的所有單元格(如FlowViewAbstractTableViewCell
  2. 在表視圖單元格子類(例如+ (CGFloat)sizeForCellWithComment:(Comment *)comment)上創建類方法。你正在做的是設置一個方法來傳遞一個模型對象到每個表視圖單元格子類可以實現的。
  3. 創建您需要從FlowViewAbstractTableViewCell繼承的許多其他單元格子類。在你的情況下,它看起來像你可以有一個叫FlowViewTextCommentTableViewCellFlowViewPictureCommentTableViewCell
  4. 對於這些子類中的每個子類,實現該方法+sizeForCellWithComment:。這將允許您根據傳入方法的對象返回可變大小。
  5. 爲您的UITableViewDelegate實施- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath。在這個方法中,你將弄清楚你想要使用哪個單元類以及哪個對象傳遞給這個尺寸方法。例如:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { Comment *commentForCell = [self.comments objectAtIndex:indexPath.row]; return [CommentTableViewCell sizeForComment:commentForCell].height; }

這將允許您返回基於對象的可變單元格高度。我一直使用可變大小的表格視圖單元格&喜歡這種模式,因爲我認爲它是隱藏實現和遵循MVC的最佳工作。

0

This video給出了一個關於使用自動佈局動態調整UITableViewCells大小的教程。當我需要爲應用程序執行此操作時,我最終創建了UITableViewCell子類並以編程方式設置了我的約束,並且它的工作方式就像一個魅力。

+0

我看到video.nothing工作。 :( – 2014-10-21 06:53:43

0

比上述

+0

我讀過但沒有爲我工作 – 2014-12-16 13:13:42

+0

嘗試自定義您的UITableViewCell,而不是使用預定義的 – Yaman 2014-12-17 09:40:12

0

試試這個

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
return [self.tableName.dataSource tableView:self.tableName cellForRowAtIndexPath:indexPath].contentView.frame.size.height; 
} 

而在你的cellForRowAtIndexPath委託,如果你正在使用的標籤 然後第一組線的數量標註爲0,然後設置標籤文本,然後添加它sizeTofit財產。像這樣

[cell.yourLabelName setNumberOfLines:0]; 
cell.yourLabelName.text = @"Your long or short text"; 
[cell.yourLabelName sizeToFit]; 

這將根據其中的文本擴展標籤高度。

之後,你可以像這樣設置你的單元格contentView的大小。

cell.contentView.frame = CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width,"Height of label" + cell.contentView.frame.size.height); 
相關問題