如何在UITableViewCell中垂直居中对齐UIButton?(Objective C)

3
我有一个自定义的表格单元格,我想在左侧垂直居中于单元格内添加一个自定义UIButton。 我尝试使用如下代码来实现,该代码位于我的自定义表格单元格实现中。
我尝试通过获取 self.frame 的高度并调整按钮的大小,使其距离单元格顶部和底部各5像素来实现垂直居中对齐。 当我运行此代码时,我看到按钮距离顶部5像素,但是距离底部相当多(大约20像素)。
如何正确实现垂直对齐?
这是我在自定义表格单元格实现中的代码:
- (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];

感谢任何建议,
Erik
2个回答

5
重写 UITableViewCell 的 layoutSubview 方法。
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.audioButton.center = CGPointMake(self.audioButton.center.x, self.contentView.center.y);
}

2
我真的很喜欢这个解决方案的优雅性。将其添加到我的 layoutSubviews 重写中,它非常好用!非常感谢。 (很遗憾我还不能给你的答案点赞。) - Erik van der Neut

3

您只需要将框架设置为与其中心相关即可。例如:

CGFloat height = self.frame.size.height - 10;
self.audioButton.frame = CGRectMake(self.contentView.frame.size.height/2-height/2, 5,height , height);

啊,对了-- 这里的诀窍是查看self.contentView.frame而不是self.frame。谢谢! - Erik van der Neut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接