-1

I have a UIButton in table cell. I want to place the button at the center of the cell. The text of the button is dynamic. This is what I have tried, but it's not coming at the center. It is coming towards the right of center.

UIButton *btnName = [UIButton buttonWithType:UIButtonTypeRoundedRect];

CGSize maximumLabelSize = CGSizeMake(self.frame.size.width, MAXFLOAT);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;

NSDictionary *attr = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
CGRect labelBounds = [titleText boundingRectWithSize:maximumLabelSize
                                             options:options
                                          attributes:attr
                                             context:nil];
CGFloat width = ceilf(labelBounds.size.width);

btnName.frame = CGRectMake(0.0, imgPic.frame.origin.y+imgPic.frame.size.height+20.0, width, 20.0);
btnName.center = CGPointMake(cell.contentView.center.x, imgPic.frame.origin.y+imgPic.frame.size.height+10.0);

[btnName setTitle:titleText forState:UIControlStateNormal];
[btnName setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[cell.contentView addSubview:btnName];
Hemang
  • 26,840
  • 19
  • 119
  • 186
Nitish
  • 13,845
  • 28
  • 135
  • 263

3 Answers3

2

Just add below line in your code.

btnName.center = cell.center;
Dipen Chudasama
  • 3,063
  • 21
  • 42
0

Your code looks fine, only you've to make these change,

  1. You should center the button after you add it cell, and

  2. Correct the center points


[cell.contentView addSubview:btnName];

btnName.center = CGPointMake(cell.frame.size.width/2.f, btnName.center.y);
Hemang
  • 26,840
  • 19
  • 119
  • 186
0

Vladimir's answer saved my day. I used setAutoresizingMask and now it is coming absolutely fine.

Community
  • 1
  • 1
Nitish
  • 13,845
  • 28
  • 135
  • 263