I have my custom UITableViewCell with UITextView in it. After UITableView loads I need to adjust the size of the UITableViewCell with size of the text in a UITextView. So I am trying to it like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtInd开发者_运维百科exPath:(NSIndexPath *)indexPath;
{
CGFloat resHeigth;
resHeigth = MyCell.textView.contentSize.height;
resHeigth += TOP_BOTTOM_MARGINS * 2;
return resHeigth;
}
But heightForRowAtIndexPath called before cellForRowAtIndexPath, where I actually set the text.
MyViewCell *cell = (MyViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"MyCellView" owner:self options:nil];
cell = MyCell;
}
cell.textView.text = @"Text for test\nTest";
CGRect frame = cell.textView.frame;
frame.size.height = cell.textView.contentSize.height;
cell.textView.frame = frame;
So, Is it possible to change the height of the UITableViewCell?
Use the methods from NSString UIKit Additions to compute the size of the text.
CGSize sz = [yourText sizeWithFont:cellTextFont constrainedToSize:CGSizeMake(textFieldWidth,CGFLOAT_MAX);
Will return the size of the text when constrainted to a fixed size and uncontrainted vertically (CGFLOAT_MAX is the maximum value for floats)
If you have the text available as NSString, then you can use NSString's instance method sizeWithFont:constrainedToSize:lineBreakMode: to measure the size that this string will take. Using that you can set the cell height in the heightForRowAtIndexPath
method.
Update: In the constrainedToSize parameter you can set the height to a very high value (maybe int max, or screen height), so it returns full height that this string takes.
精彩评论