Reputation: 2245
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
Upvotes: 3
Views: 4980
Reputation: 6445
You just need to set the frame with related to it's center. ie,
CGFloat height = self.frame.size.height - 10;
self.audioButton.frame = CGRectMake(self.contentView.frame.size.height/2-height/2, 5,height , height);
Upvotes: 3
Reputation: 3793
Override layoutSubview
method of UITableViewCell.
- (void)layoutSubviews
{
[super layoutSubviews];
self.audioButton.center = CGPointMake(self.audioButton.center.x, self.contentView.center.y);
}
Upvotes: 5