0

I have UITextViews in UITableViewCells. What I want to do is make the cell fit the textView If the cell contains a textView. I can make a if statement for every cell and return the textView's size, (I have more than 1 cell with a textView) as I started in the code below, but I'm sure there is another way of doing this.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        return myTextview.frame.size.height + 40;
    }
    return 44;
}

I'm a beginner, so please don't be too harsh.

2 Answers2

0

first decide if the cell is consisting of UITextView or not.if yes according to textview size give the row height.(But make sure your adding the textview to the content view of cell)

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIView *tempView in  [[tableView cellForRowAtIndexPath:indexPath].contentView subviews])
    {      
        if (tempView isKindOfClass:[UITextView Class])
        {          
            return  tempView.frame.size.height + 40;

             //(or) for dynamic cell height
            //CGSize Size=  [tempView.text boundingRectWithSize:CGSizeMake(200, 1000000)
                                                   options:NSLineBreakByWordWrapping |
                                                  NSStringDrawingUsesLineFragmentOrigin
                                                          attributes:@{
                        NSFontAttributeName :[UIFont fontWithName:@"Helvetica" size:12]
                                                                      }    
                                                        context:nil].size;
             //return Size.height;
         }
     }    
     return 44;
}
-1

you can always do it in cell class,declare a method and name it, for example ,

layoutCellByString:(NSString *) stringContent, measure and adjust cell height

and declare another method call getCellHeight in cell class, and return self.frame.size.height;

and in heightForRowAtIndexPath, you can do this:

YourCellClassName *cell = (YourCellClassName *)[self tableView:self.tableView cellForRowAtIndexPath:indexPath];

return [cell getCellHeight];

you should call layoutCellByString in cellForRowAtIndexPath in order to make this work

ps: apologize for the pool english by the way.

Dharma
  • 3,007
  • 3
  • 23
  • 38
7heaven
  • 797
  • 7
  • 16