1

I have a custom UIButton in a custom UITableViewCell. I want to set the height of the UIButton in the custom table cell based on the variable textual content of the titleLabel of the button.

I tried the following method to calculate the height

[NSString sizeWithFont:constrainedToSize:lineBreakMode:];

but I could not successfully change the button height as per the titleLabel.

Further, as this button is part of a custom UITableViewCell, I also need to change the height of the cell as per the height of the custom UIButton.

In the ViewController implementing the delegate and the datasource methods of the UITableView, I tried to determine the height in the following method

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

but was not successful.

What could be the best solution or approach to solve this?

An1Ba7
  • 355
  • 11
  • 25
  • 1
    See my answer here - http://stackoverflow.com/questions/12506313/dynamic-size-of-uitablecell-hight/12506358#12506358 – TheTiger Sep 21 '12 at 18:45

3 Answers3

4

Assume the width of your button is 145.0f:

CGSize constraintSize;

constraintSize.width = 145.0f;

constraintSize.height = MAXFLOAT;

CGSize size = [Label.text sizeWithFont:Label.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

Then you can set the frame:

frame = CGRectMake(0, 0, 145, size.height);
Suresh Varma
  • 9,750
  • 1
  • 60
  • 91
Peter Zhou
  • 3,881
  • 2
  • 21
  • 19
2

It seems like you do it right, but remember:

heightForRowAtIndexPath must return CGFloat sizeWithFont gives you height of text, you need to add padding of your button, and cell

use constrainedToSize:CGSizeMake(###,MAXFLOAT) where ### is your text width

lineBreakMode:UILineBreakModeWordWrap of course

cyborg86pl
  • 2,597
  • 2
  • 26
  • 43
1

You can also use [buttonInstance sizeToFit].

 UIButton *lineButton = [[UIButton alloc] initWithFrame:CGRectZero];
 // If padding equals "yes, please"
 [lineButton setContentEdgeInsets:UIEdgeInsetsMake(0.0f, 5.0f, 0.0f, 3.0f)];
 [lineButton setTitle:@"Title" forState:UIControlStateNormal];
 [lineButton sizeToFit];
Cameron Lowell Palmer
  • 21,528
  • 7
  • 125
  • 126