how to set UITextView height dynamically inside a custom UITableViewCell with autolayout

Viewed 12662

I have UITableView, every tableViewCell is custom. Inside my customTableViewCell is a UITextView, TextViews frame is pin or same as its superView which is tableViewCell. enter image description here

How Am I gonna set the UITableViewCell height dynamically that is proportional to the TextViews size which will also depends to content text that I get from internet.

(sample prototype)

enter image description here

// this is how I manipulate every cell height

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // How do I set the height here, whats the best approach for this. with autolayout BTW
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.
}
3 Answers

Primarily get the texts as NSArray and Assign it into the UITextView's as temporary, So that you will get the Height of Cell :

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        CGRect frame;
        //  set the height here, According to the NSArray of text 
        if(textView || section )
        UITextView *tempTxtView = [[UITextView alloc] init];
        tempTxtView.text = // Add the Text of index according to the Section
        // Fit  the  UITextView to the Content 
        frame = tempTxtView.frame;
        frame.size.height = tempTxtView.contentSize.height;
        tempTxtView.frame = frame;
    }    
    return frame.size.height;
 }

Once got the UITableViewCell height : Then No need to worry about this, right ?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.

self.textView =  [[UItextView alloc] initWithFrame:CGRectMake(cell.frame.origin.x +20, cell.frame.origin.y +10, cell.frame.size.width - 20, cell.frame.size.height - 20)];

// ....... Do further with the NSArray of Text


}

Note : I Haven't Tested, Its just a thought. Hope this will help you

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
      CGSize titlesize = [TxtValue.text sizeWithFont:[UIFont fontWithName:appdel.strFont size:25.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];  /// ----- -set width as per your requirement inplace of 300 

      return titlesize.height+10;
 }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

}
Related