Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

ipad - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...