Ios 如何在UITableViewCell中垂直居中对齐UIButton?(目标C)
我有一个自定义表格单元格,我想在其左侧添加一个自定义UIButton,在单元格内垂直居中。我试图用下面所示的代码来实现这一点,这是在我的自定义表单元实现中 我试图通过测量self.frame的高度并调整按钮大小,使其从单元格的顶部和底部显示5px,来实现垂直中心对齐。当我运行这个程序时,我看到按钮从顶部显示5px,但从底部显示更多(20px左右) 实现垂直对齐的正确方法是什么 这是我在自定义表格单元格实现中的代码:Ios 如何在UITableViewCell中垂直居中对齐UIButton?(目标C),ios,objective-c,uitableview,uibutton,vertical-alignment,Ios,Objective C,Uitableview,Uibutton,Vertical Alignment,我有一个自定义表格单元格,我想在其左侧添加一个自定义UIButton,在单元格内垂直居中。我试图用下面所示的代码来实现这一点,这是在我的自定义表单元实现中 我试图通过测量self.frame的高度并调整按钮大小,使其从单元格的顶部和底部显示5px,来实现垂直中心对齐。当我运行这个程序时,我看到按钮从顶部显示5px,但从底部显示更多(20px左右) 实现垂直对齐的正确方法是什么 这是我在自定义表格单元格实现中的代码: - (id)initWithStyle:(UITableViewCellStyl
- (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覆盖UITableViewCell的方法
- (void)layoutSubviews
{
[super layoutSubviews];
self.audioButton.center = CGPointMake(self.audioButton.center.x, self.contentView.center.y);
}
您只需要设置与中心相关的框架。即
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。谢谢我真的很喜欢这个解决方案的优雅。将其添加到我的
布局子视图中
覆盖,效果非常好!非常感谢。(不幸的是,我还不能对你的答案投弃权票。)