简体   繁体   中英

iOS calculate text height in tableView cell

i'm currently developing on an app, which displays some tweets in a tableview. On the storyboard i created a prototype-cell, which includes the basic gui concept of a tweet entry.

It looks circa like this:

++++++++++++++
++Username++++
++++++++++++++
++Tweet+++++++
++++++++++++++
++Time-Ago++++
++++++++++++++

Now i'm calculating the height of the cell with the following code, but somehow it fails.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary * currentTweet = [tweetArray objectAtIndex: indexPath.row];
    NSString * tweetTextString = [currentTweet objectForKey: @"text"];
    CGSize textSize = [tweetTextString sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(630, 1000) lineBreakMode: NSLineBreakByWordWrapping];

    float heightToAdd = 24 + textSize.height + 15 + 45;
    if(heightToAdd < 90) {
        heightToAdd = 90;
    }

    return heightToAdd;
}

By the way, there is something other, which is strange. If i scroll the tableview the whole app seems to freeze. Is this normal or am i doing something wrong?

Try this for your issue:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary * currentTweet = [tweetArray objectAtIndex: indexPath.row];

    NSString * tweetTextString = [currentTweet objectForKey: @"text"];

    CGSize textSize = [tweetTextString sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(240, 20000) lineBreakMode: UILineBreakModeWordWrap]; //Assuming your width is 240

    float heightToAdd = MIN(textSize.height, 100.0f); //Some fix height is returned if height is small or change it to MAX(textSize.height, 150.0f); // whatever best fits for you

    return heightToAdd;
}

Hope it helps.

If you are looking for the iOS 7 answer I ran across it here:

iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM