Domanda

I have a twitter like UITableViewCell that displays the user image, user name, tweet and buttons for reply, retweet and favourite. I went through a couple of sites that teach how to autolayout tables in ios. This one made sense Table Layout Blog, but I cannot get it to work. I know I need to work with two methods heightForRowAtIndexPath and cellForRowAtIndexPath. In addition I have a configureCell:cell that fills out the cell with the data. Here is my implementation based on the blog.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TweetCell";
    TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [self configureCell:cell forIndexPath:indexPath isForOffscreenUse:NO];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.prototypeCell)
    {
        self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"TweetCell"];
    }

    [self configureCell:self.prototypeCell forIndexPath:indexPath isForOffscreenUse:YES];

    [self.prototypeCell layoutIfNeeded];
    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    NSLog(@"%f",size.height);
    return size.height;
}

-(void) configureCell:(TweetCell*)cell forIndexPath:(NSIndexPath*)indexPath isForOffscreenUse:(BOOL)isForOffscreenUse{
    Tweet *tweet = self.tweets[indexPath.row];
    cell.tweetText.text = tweet.text;
    NSURL *url = [NSURL URLWithString:[tweet imageURLFromTweet]];
    [cell.tweetImageView setImageWithURL:url];
    cell.tweetImageView.contentMode = UIViewContentModeScaleAspectFit;
    cell.tweetUserName.text = [tweet usernameFromTweet];
}

The problem is that heightForRowAtIndexPath size.height is 0. Can somebody please help out? Thanks.

È stato utile?

Soluzione

At heightForRowAtIndexPath the cell will not be created. You need to measure the height of your content independent of the cell.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Tweet *tweet = self.tweets[indexPath.row];
    CGFloat height = [tweet.text sizeWithFont:[Your Font] constrainedToSize:[CGSizeMake(Your Cell Width, CGFLOAT_MAX)];
    NSURL *url = [NSURL URLWithString:[tweet imageURLFromTweet]];
    UIImage *image = [Get your image and cache it so you can the set it during configureCell];
    height += image.size.height;

    return height;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top