2011-12-14 78 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也是一个不错的主意同意。

相关问题