开发者

How to get height of dynamically created UITextView iphone

I am trying to create a table with cells that contain UITextViews inside them for variable amounts of text. I need to specify the height of each cell t开发者_Go百科o match the content size of the textviews. I am using...

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

    UITextView *historyNode = [[[UITextView alloc]init]autorelease];
    historyNode.text = (@"%@",[globalArrayWithStrings objectAtIndex:[indexPath row]]);
    NSLog(@"%2.0f",historyNode.frame.size.height);
    return historyNode.contentSize.height;
}

For some reason, it always prints 0. If i print the height of a textview created in interface builder, it prints the correct value. Any ideas how to get around this or why I can't get the size of a textview until it is added to the view.


You can use the sizeWithFont: method to find the dynamic height. Your heightForRowAtIndexPath: should look like this.

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

    NSString *text = [globalArrayWithStrings objectAtIndex:[indexPath row]];
    CGSize maxSize = CGSizeMake(textViewWidth, 999); // 999 can be any maxmimum height you want
    CGSize newSize = [text sizeWithFont:aFont constrainedToSize:maxSize lineBreakMode:textViewLineBreakMode];
    return newSize.height;
}


First set the frame of the uitextView and then you will get the height of the text view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜