Reputation: 1976
I am trying to get my UITableViewCell
to resize properly based off a textview
which is dynamically sized based off it's text. However I can't get them to all work together. Below is what I have so far? Right now the cell height is correct, but the textView
isn't being resized based off the contentSize.height
.
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the label properties!
self.titleLabel.text = self.releaseTitle;
self.pubDateLabel.text = self.pubDate;
self.attachmentsLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.attatchments.count];
self.contentTextView.text = self.summary;
}
- (void)viewWillAppear:(BOOL)animated
{
}
- (void)viewDidAppear:(BOOL)animated
{
[self.tableView reloadData];
// Set the proper height of the content cell of the text
CGRect frame = self.contentTextView.frame;
frame.size.height = self.contentTextView.contentSize.height;
self.contentTextView.frame = frame;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return self.contentTextView.contentSize.height;
}
Upvotes: 0
Views: 1263
Reputation: 869
You need to calculate the height of the cell in heightForRowAtIndexPath,
something like
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *theText=[[_loadedNames objectAtIndex: indexPath.row] name];
CGSize labelSize = [theText sizeWithFont:[UIFont fontWithName: @"FontA" size: 15.0f] constrainedToSize:kLabelFrameMaxSize];
return kHeightWithoutLabel+labelSize.height;
}
You can set some constraints on the label size by setting kLabelFrameMaxSize
#define kLabelFrameMaxSize CGSizeMake(265.0, 200.0)
Then you return the height by adding a constant height with the variable label height.
Also, to be consistent, you should use the same methodology to set the frame in cellForRowAtIndexPath
instead of using sizeToFitMultipleLines
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
FQCustomCell *_customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
if (_customCell == nil) {
_customCell = [[FQCustomCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
}
_customCell.myLabel.text = [[_loadedNames objectAtIndex: indexPath.row] name];
_customCell.myLabel.font = [UIFont fontWithName: @"FontA" size: 15.0f];
UIView *backView = [[UIView alloc] initWithFrame: CGRectZero];
backView.backgroundColor = [UIColor clearColor];
_customCell.backgroundView = backView;
CGSize labelSize = [_customCell.myLabel.text sizeWithFont:_customCell.myLabel.font constrainedToSize:kLabelFrameMaxSize];
_customCell.myLabel.frame = CGRectMake(5, 5, labelSize.width, labelSize.height);
return _customCell;
}
You can alter this for UILabel, UIButton, Cell.
Upvotes: 1