如何以编程方式设置UIButton的垂直对齐方式 – iOS

我知道如何设置按钮与IB的垂直对齐方式; 看到这里 。 但我不能以编程方式做到这一点……这是我尝试过的事情之一:

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(我不想要默认的外观)。

您可以通过以下方式对齐(水平和垂直)按钮文本:

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

contentVerticalAlignment是要走的路。 可能是你创建按钮的方式。 尝试这个:

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

问题是使用

 button.titleLabel.textColor = [UIColor grayColor]; 

代替

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

在我的代码的其他地方,我仍然有垂直对齐文本的麻烦,但我已经得到了基本的例子,所以如果我更多地看它,我应该能够得到更复杂的版本。 也许我正在使用其他方法,如button.titleLabel.textColor,这使得垂直对齐不起作用…

更新原始问题实际上是因为我的按钮太短(按钮高度)。

“丈夫”这个词在按钮中

husband一词在按钮中,当前垂直对齐底部。 但由于按钮的高度不够,所以并不明显。 尽管标题插入内容和内容插入的默认值为零,但似乎标题不能与底部齐平。 它看起来像我约5个像素。 我用较小的字体测试,以确保这是正确的。

不幸的是,将文本垂直对齐到顶部似乎没有改变任何东西……

您可以轻松地操作UIButton的内部文本标签。 在这里你可以这样做:

  1. 将按钮的文本设置为@“”(空字符串)
  2. 创建新的UILabel并调整它的框架
  3. 在按钮的视图中插入创建的UILabel作为子视图
  4. 完成。 现在,您可以通过更改其框架属性以编程方式设置内部UILabel的位置。

我找到了一种适合我的更好方法。 我正在使用一个自定义字体,所以对齐有点像lindon fox上面的答案。

你内部的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答案也是一个好主意。