iProgrammer Tip #3: Multiline text in UITableViewCell (without custom view)
The trouble with UITableViewCell is it doesn’t handle multiline text by default!
So if you want to have multiline text in your table view, you might be tempted to create Customview and drawRect. But there is another way!
Its 2 step process!
Step 1: Calculate required Height of each row and send the info to Tableview by implementing
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = // Your text to be displayed
UIFont *font = [UIFont fontWithName:@"Helvetica" size:17.0]; // You can choose a different font ofcourse.
CGSize withinsize = CGSizeMake(tableView.frame.size.width, 1000); //1000 is just a large number. could be 500 as well
// You can choose a different Wrap Mode of your choice
CGSize sz = [str sizeWithFont:font constrainedToSize:withinsize lineBreakMode:UILineBreakModeWordWrap];
return sz.height + paddingspace; // padding space of 20 should be fine!
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @”Cell”;
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGRect rectLabel = CGRectMake(cell.frame.origin.x+20, cell.frame.origin.y+10, cell.frame.size.width-20, cell.frame.size.height-20);
UILabel* label = [[UILabel alloc] initWithFrame:rectLabel];
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
label.font = [UIFont fontWithName:@"Helvetica" size:17.0]; //Same font used for calculating height
label.text = [tweets objectAtIndex:indexPath.row];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell addSubview:label];
[label release];
}
return cell;
}