2013-09-26 82 views
2

我有一個自定義表單元格,我想在左側添加一個自定義UIButton,在單元格內垂直居中。我試圖用下面顯示的代碼來做到這一點,這是我的自定義表格單元實現。如何在UITableViewCell中垂直居中對齊UIButton? (Objective C)

我試圖通過採取self.frame的高度和調整按鈕的大小來實現垂直中心對齊,使其從單元格的頂部和底部出現5px。當我運行這個時,我看到按鈕出現在頂部5px,但從底部(20px左右)顯着更多。

什麼是實現垂直對齊的正確方法?

這是我自定義表格單元格的實現代碼:

- (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]; 

感謝您的任何建議,

埃裏克

回答

3

你只需要設置相關的框架中心。即,

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

啊,對 - 這裏的技巧是看self.contentView.frame而不是self.frame。謝謝! –

4

覆蓋的UITableViewCell的layoutSubview方法。

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

我真的很喜歡這種解決方案的優雅。補充說,我的'layoutSubviews'覆蓋,它的作品非常漂亮!非常感謝。 (不幸的是,我不允許爲你的答案提供投票權。) –