Reputation: 3709
I wnat my cell's height to change depending on the text being displayed in it. The text will vary and I'm basically wanting the cells to change size. Here is what I have so far:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefaultCell1"];
CGRect cellRectangle;
if (cell == nil) {
cellRectangle = CGRectMake(0.0, 0.0, 300, 110);
cell = [[[UITableViewCell alloc] initWithFrame:cellRectangle reuseIdentifier:@"DefaultCell1"] autorelease];
}
UILabel *label;
cellRectangle = CGRectMake(10, (40 - 20) / 2.0, 280, 110);
//Initialize the label with the rectangle.
label = [[UILabel alloc] initWithFrame:cellRectangle];
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 20;
label.font = [UIFont fontWithName:@"Helvetica" size:11.0];
label.text = [[self.person.statusMessages objectAtIndex:indexPath.row] valueForKey:@"text"];
CGFloat height = [label.text sizeWithFont:label.font].height;
//So right here is where I think I need to do something with height and
//see it to something tied to he cell
[cell.contentView addSubview:label];
[label release];
return cell;
}
Upvotes: 4
Views: 12559
Reputation: 1011
If all the rows are of the same height, which I think is true in your case, you can setRowHeight in your tableview Controller.
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
self = [super initWithStyle:style];
if (self) {
// Custom initialization.
NSLog(@"%s", __FUNCTION__);
[self.tableView setRowHeight:110];
}
return self;
}
The row width can be controlled by the table's superview width
Upvotes: 3
Reputation: 8924
You shouldn't set the height in the cellForRowAtIndexPath method. there's another UITableViewDatasource method called tableView:heightForRowAtIndexPath: which you should implement to return the cell's height. Be careful using this though; you mustn't obtain the cell at that index path within this method; if you do you will construct an infinite recursive loop.
Edit: to be clear; you need to compute the cell's height based solely on it's content and not on the cell itself.
Also, in your code where you create the cell, you can just pass in CGRectZero to the frame argument; the table view will calculate the cell's frame itself if you do (and also explicitly passing in the frame is deprecated in OS 3.0 if I recall correctly).
Upvotes: 8