ios - 如何在 UITableViewCell 中垂直居中对齐 UIButton? ( objective-c )

标签 ios objective-c uitableview uibutton vertical-alignment

我有一个自定义表格单元格,我想在左侧添加一个自定义 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];

感谢您的任何建议,

埃里克

最佳答案

重写 UITableViewCell 的 layoutSubview 方法。

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

关于ios - 如何在 UITableViewCell 中垂直居中对齐 UIButton? ( objective-c ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19020523/

相关文章:

ios - NSURLComponents 获取百分比编码

ios - Xamarin 窗体 : How to change background from gray on selected item in listview, iOS

ios - 从 URL 下载音频文件并在 iOS 应用程序中播放

ios - UIButton 选择滑过

ios - 等到对象可用

iOS - 具有约束的多行 UILabel 高度

objective-c - 如何在 iphone 屏幕顶部(状态栏下方)添加一个栏?

swift - 如何隐藏/显示某些 UIView 的 UI 导航栏

iphone - SectionHeader 打开/关闭动画

ios - 在 Swift 中,如何在 TableView 的 TableViewCell 中的 UIImageView 上添加角标(Badge)?