如何在UITableViewCell中垂直对齐UIButton?(目标C)

Eri*_*eut 3 objective-c vertical-alignment uibutton uitableview ios

我有一个自定义表格单元,我想在左侧向其中添加一个自定义UIButton,使其垂直居中。我尝试使用下面显示的代码来实现此目的,这些代码在我的自定义表格单元实现中。

我正在尝试通过获取self.frame的高度并调整按钮的大小来实现垂直居中对齐,以使其从单元格的顶部和底部出现5px。当我运行此按钮时,我看到按钮从顶部出现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];
Run Code Online (Sandbox Code Playgroud)

感谢您的任何建议,

埃里克

Onk*_*arK 5

layoutSubviewUITableViewCell的重写方法。

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.audioButton.center = CGPointMake(self.audioButton.center.x, self.contentView.center.y);
}
Run Code Online (Sandbox Code Playgroud)

  • 我真的很喜欢这种解决方案的优雅。将其添加到我的`layoutSubviews`覆盖中,并且效果很好!非常感谢。(不幸的是,我尚未被允许对你的答案进行投票。) (2认同)