2011-12-14 129 views
15

我知道如何設置IB對齊按鈕的垂直對齊方式;見here。但我不能這樣做編程...這是我試過的事情之一:如何以編程方式設置UIButton的垂直對齊 - iOS

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 110, 130)]; 
[button setTitle:@"Align" forState:UIControlStateNormal]; 
button.backgroundColor = [UIColor whiteColor]; 
button.titleLabel.textColor = [UIColor grayColor]; 
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom]; 

[self.view addSubview:button]; 

[button release]; 

我也曾嘗試插圖...

但對準不會改變。

請注意,我想保留按鈕的CustomStyle(我不想要默認的外觀和感覺)。

回答

1

的問題是使用

button.titleLabel.textColor = [UIColor grayColor]; 

,而不是

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

其他地方在我的代碼,我仍然有麻煩垂直對齊文本的,但我已經拿到了基本的例子,所以我應該能夠得到更復雜的版本,如果我看更多。也許還有其他的方法,我使用像button.titleLabel.textColor這使得垂直對齊方式無法正常工作......

更新 原來的問題實際上是因爲我的按鈕太矮(身高按鈕)。

The word `husband' is in the button

husband是在按鈕,這是目前垂直對齊於底部。但由於按鈕的高度不夠,所以不明顯。儘管標題插入和內容插入的默認值爲零,但標題看起來並不像底部。它看起來像我約5個像素。我用較小的字體進行測試以確保這是正確的。

不幸的是垂直對齊文本頂端似乎並沒有改變什麼......

9

contentVerticalAlignment是要走的路。可能是你如何創建按鈕。試試這個:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
button.frame = CGRectMake(10, 10, 110, 130); 
// rest of your code 
// don't release button explicitly 
+0

+1用於回答我的問題100%。但是我不會告訴你,因爲你沒有讀懂我的想法......對不起,我應該更好地指出這個問題。我也想保留自定義類型。我會修改我的問題以反映這一點。如果沒有更好的答案出現,我會給你打勾。乾杯。 – 2011-12-15 01:36:32

+0

有趣的是,當你(錯誤地)通過訪問titleLabel(而不是發送setTitleColor消息)來改變字體顏色時,這將停止工作 – 2011-12-15 01:39:19

1

你可以很容易地操作的UIButton的內部文本標籤。 在這裏你可以怎麼做:

  1. 組按鈕的文字@「」(空字符串)
  2. 創造新的UILabel和調整它的框架
  3. 創建的UILabel按鈕內的視圖子視圖
  4. 插入
  5. 這是完成。現在你可以通過編程來設置UILabel的內部位置,並改變它的框架屬性。
18

您可以對齊(水平和垂直)按鈕,這樣的文字:

 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 70)]; 
     button.backgroundColor = [UIColor whiteColor]; 
     button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 
     button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom; 
     [button setTitle:@"Align" forState:UIControlStateNormal]; 
     [self.container addSubview:button]; 
0

我發現對我的作品更好的辦法。我正在使用自定義字體,所以對齊方式有點像上面的lindon fox's答案中的一些。

你內心的UIButton子類:

- (void)layoutSubviews { 

     [super layoutSubviews]; 

     if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.titleEdgeInsets)) { 

      // adjust top, left bottom, and right to fit your needs 
      self.titleEdgeInsets = UIEdgeInsetsMake(top, left, bottom, right); 
     } 
} 

我與其他的答案,使用contentVerticalAlignment設置爲UIControlContentVerticalAlignmentCenter也是一個不錯的主意同意。