gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:08:02 30 4
gpt4 key购买 nike

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com