how to set UITextView height dynamically inside a custom UITableViewCell with autolayout
Solution 1
Follow this answer: Link reference
Add a height constraint to your UITextView and create an outlet to your custom cell class.
Use
sizeThatFits:
onUITextView
to get the size that fits the content and set this value as aconstant
of the constraint described in 2. Do this intableView:heightForRowAtIndexPath:
.
One caveat is that if there're many cells (hundreds or thousands) then you may hit performance issues.
Solution 2
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
Bordz
Updated on July 26, 2022Comments
-
Bordz almost 2 years
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.
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)
// 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. }
-
Arek Holko almost 10 years@Spail: can you check if the correct size is returned from the call to
sizeThatFits:
? -
Spail almost 10 yearsyeah, the size returned is kinda strange. its width is larger than it should be. can you post your code for this?
-
Spail almost 10 yearsNevermind, I forgot to add +1 to height to account for the cell separator. Seems like it works now. Thanks.