Tuesday, February 9, 2010

Dynamic Height for UITextView / UILabel / UITableViewCell

we can use this for calculating the height taken by a UILabel or UITextView or we can use this same method to calculate the height of cell according to its content..

CGRect frame1 = CGRectMake(5.0, 100.0, 300.0, 75.0 ); UITextView *textView = [[UITextView alloc] initWithFrame:frame1]; textView.font = [UIFont systemFontOfSize:17.0]; NSString *str = @"The Lord takes care of me as his sheep; I will not be without any good thing."; CGSize textSize = { 300.0f, 9999.0f }; CGSize size1 = [str sizeWithFont:textView.font constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap]; textView.text = str; frame1.size.height = size1.height; textView.frame = frame1; [self.view addSubview:textView]; [textView release];

For UITableView
we can use like
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//calculate the height of the text displayed on this cell using the above method
return MAX(size1.height, kMinRowHeight);

No comments:

Post a Comment