Search code examples
iosobjective-cuitableviewautolayoutcalayer

Get the size of UIButton inside a custom UITableViewCell with Autolayout


I have an UIButton inside a custom UITableViewCell created in Interface Builder, the height and width is defined by Autolayout constraints.

I need to get the size of the UIButton after autolayout define the final size.

UITableViewCell with Autolayout

what I have tried:

Inside my custom UITableViewCell

 - (void)layoutSubviews
 {
    [super layoutSubviews];

  NSLog(@"%f", self.infoButton.bounds.size.width);

    self.infoButton.layer.cornerRadius   = self.infoButton.bounds.size.width/2;
    self.infoButton.clipsToBounds        = YES;
    self.infoButton.layer.borderColor    = [UIColor whiteColor].CGColor;
    self.infoButton.layer.borderWidth    = 4.0f;
}

The problem is that I have different values :

2015-06-30 03:01:47.578 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.581 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.583 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:47.585 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:47.586 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:47.586 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:53.482 MYPROJ[3596:34092] 48.000000
2015-06-30 03:01:53.484 MYPROJ[3596:34092] 56.000000
2015-06-30 03:01:54.939 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:04.161 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:05.115 MYPROJ[3596:34092] 56.000000
2015-06-30 03:02:05.957 MYPROJ[3596:34092] 56.000000

I have also tried the code inside - (void)awakeFromNib I tried both self.infoButton.bounds.size.width and self.infoButton.frame.size.width

and it gives me the static width before Autolayout which is in my case 48.0 Also

I am afraid the solution of putting the code inside - (void)layoutSubviews can affect performance since it will be called everything the user scroll and apply the layer transformation every time, is there any better solution ?


Solution

  • In your custom UITableViewCell.m file, add following lines in your awakeFromNib method.

    Here, as your button is dependent on cell and which indeed has same width as device's screen.

    - (void)awakeFromNib {
    // Initialization code
    self.infoButton.layer.cornerRadius   = [UIScreen mainScreen].bounds.size.width * 0.075f; // 0.15/2 = 0.075f (Half of the button's width)
    self.infoButton.clipsToBounds        = YES;
    self.infoButton.layer.borderColor    = [UIColor whiteColor].CGColor;
    self.infoButton.layer.borderWidth    = 4.0f;
    }
    

    Hope it helps...