UITableView with dynamic cell heights -- what do I need to do to fix scrolling down?
Posted
by Ian Terrell
on Stack Overflow
See other posts from Stack Overflow
or by Ian Terrell
Published on 2009-03-25T02:56:56Z
Indexed on
2010/05/03
23:18 UTC
Read the original article
Hit count: 274
I am building a teensy tiny little Twitter client on the iPhone. Naturally, I'm displaying the tweets in a UITableView, and they are of course of varying lengths. I'm dynamically changing the height of the cell based on the text quite fine:
- (CGFloat)heightForTweetCellWithString:(NSString *)text {
CGFloat height = Buffer + [text sizeWithFont:Font constrainedToSize:Size lineBreakMode:LineBreakMode].height;
return MAX(height, MinHeight);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = // get tweet text for this indexpath
return [self heightForTweetCellWithString:text];
}
}
I'm displaying the actual tweet cell using the algorithm in the PragProg book:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TweetCell";
TweetCell *cell = (TweetCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self createNewTweetCellFromNib];
}
cell.tweet.text = // tweet text
// set other labels, etc
return cell;
}
When I boot up, all the tweets visible display just fine. However, when I scroll down, the tweets below are quite mussed up -- it appears that once a cell has scrolled off the screen, the cell height for the one above it gets resized to be larger than it should be, and obscures part of the cell below it. When the cell reaches the top of the view, it resets itself and renders properly. Scrolling up presents no difficulties.
Here is a video that shows this in action: http://screencast.com/t/rqwD9tpdltd
I've tried quite a bit already: resizing the cell's frame on creation, using different identifiers for cells with different heights (i.e. [NSString stringWithFormat:@"Identifier%d", rowHeight]
), changing properties in Interface Builder...
If there are additional code snippets I can post, please let me know. Thanks in advance for your help!
© Stack Overflow or respective owner