Reputation: 877
I am trying to make a Twitter client with XCode 4.2
. (iOS version 5
.) I want my application's main timeline to look similar to the Twitter iOS app's timeline:
I am using a UITableView
with a prototype cell containing a label and three buttons. Below is the code I'm using to set the height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = @"TweetContainerCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
@try {
UILabel* tweetLabel;
if(cell != nil) {
tweetLabel = (UILabel*)[cell.contentView viewWithTag:1];
NSString* tweetText = tweetLabel.text;
CGSize expectedLabelSize = [tweetText sizeWithFont:[UIFont fontWithName:tweetLabel.font.fontName size:20] constrainedToSize:CGSizeMake(CGFLOAT_MIN, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
//[tweetLabel setFrame:CGRectMake(tweetLabel.frame.origin.x, tweetLabel.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)];
//[cell.textLabel setFrame:tweetLabel.bounds];
//[tweetLabel sizeToFit];
//[cell setFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)];
//[cell sizeToFit];
NSLog(@"Font size: %f", expectedLabelSize.height);
return (expectedLabelSize.height * 2);
}
}
/* Imgur URL: http://i.imgur.com/lHnsAsP.png */
/* http://i.imgur.com/hA9EKfI.png */
@catch (NSException* exception) {
NSLog(@"Exception: %@", exception);
}
return 0;
}
However, this is what my app ends up looking like:
The problems are:
1) Each cell seems to have the same height as the tallest cell in the whole table, instead of having different heights.
2) Because of this, the space between the cell's top border and the text is different for each cell (because iOS
centers the text vertically).
I am learning iOS
development and being unable to do such a simple thing, even after doing a lot of research and spending a lot of hours, seems really discouraging. Any help is greatly appreciated.
(In case the information I have given is not enough, here's the ZIP file containing the whole project: https://db.tt/m5suxWCj)
Upvotes: 2
Views: 815
Reputation: 881
Your problem is that your label has not been created, since tableView:heightForRowAtIndexPath:
is initially called before tableView:cellForRowAtIndexPath:
, which is where your cell is created. In tableView:heightForRowAtIndexPath:
you should determine the height of the cell as efficiently as possible, without involving UIViews.
To achieve this, you should store the NSString
elsewhere in your table view data source, and calculate expectedLabelSize
based on that.
Note also that sizeWithFont:
is deprecated in IOS 7, so for IOS 7 and beyond you should use sizeWithAttributes:
instead.
Upvotes: 2