Change cell height in table view Goal C

I will change the height of my cell depending on the text displayed in it. The text will change, and I basically want the cells to resize. Here is what I still have:

- (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; } 
+4
source share
2 answers

You should not set the height in the cellForRowAtIndexPath method. there is another UITableViewDatasource method called tableView: heightForRowAtIndexPath: which you must implement to return the height of the cell. Be careful using this; You should not get a cell along this pointer path in this method; if you do, you will build an infinite recursive loop.

Edit: be clear; you need to calculate the height of the cell based solely on it, and not on the cell itself.

In addition, in your code where you create the cell, you can simply pass the frame argument to CGRectZero; in the table view, the cell frame itself will be calculated if you do this (as well as explicit transmission in the frame is deprecated in OS 3.0, if I remember correctly).

+8
source

If all rows have the same height, which, in my opinion, is true in your case, you can set RowHeight 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 width of the table label

+3
source

All Articles