Friday, December 2, 2011

Method to dynamically set the height of UILabel, UITableViewCell etc

To find the height of a label , UITableViewCell or UITextView for dynamic string content. Following method may help


- (float)getHeightFortheDynamicLabel:(NSString *)stringForTheLabel{
    UITextView *aSampleTextView;
    // 30 is the minimum height
    aSampleTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, mywidth, 30)];
    aSampleTextView.text = stringForTheLabel;
    aSampleTextView.font = [UIFont systemFontOfSize:kMyFontSize];
    aSampleTextView.alpha = 0;
    [self.view addSubview:aSampleTextView];
    float textViewHeight = aSampleTextView.contentSize.height;
    [aSampleTextView removeFromSuperview];
    [aSampleTextView release];
    return  textViewHeight;
}

2 comments: