Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically center align UIButton in UITableViewCell? (Objective C)

I have a custom table cell to which I want to add a custom UIButton on the left side, vertically centered within the cell. I tried to do that with the code shown below, which is in my custom table cell implementation.

I'm trying to achieve the vertical center alignment by taking the height of self.frame and sizing the button such that it would appear 5px from the top and bottom of the cell. When I run this, I see that the button appears 5px from the top, but considerably more from the bottom (20px or so).

What is the proper way to achieve the vertical alignment?

This is my code in the custom table cell implementation:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
  self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  if (self)
  {
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];

    // Create the audio button on the left side:
    self.audioButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.audioButton.frame = CGRectMake(5, 5, self.frame.size.height - 10, self.frame.size.height - 10);
    [self.audioButton setImage:[UIImage imageNamed:@"ec-icon-speaker.png"] forState:UIControlStateNormal];
    [self.audioButton addTarget:self
                    action:@selector(playWordAudio)
          forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.audioButton];

Thanks for any suggestions,

Erik

like image 237
Erik van der Neut Avatar asked Nov 30 '25 08:11

Erik van der Neut


1 Answers

Override layoutSubview method of UITableViewCell.

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.audioButton.center = CGPointMake(self.audioButton.center.x, self.contentView.center.y);
}
like image 143
OnkarK Avatar answered Dec 02 '25 23:12

OnkarK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!