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

lin*_*fox 20 cocoa-touch 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];
Run Code Online (Sandbox Code Playgroud)

我也尝试了插图......

但是对齐不会改变.

请注意,我想保留按钮的CustomStyle(我不想要默认的外观).

Ale*_*ano 22

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

        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];
Run Code Online (Sandbox Code Playgroud)


XJo*_*nes 9

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

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


lin*_*fox 1

问题是使用

button.titleLabel.textColor = [UIColor grayColor];
Run Code Online (Sandbox Code Playgroud)

代替

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

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

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

按钮上有“丈夫”一词

该单词husband位于按钮中,当前与底部垂直对齐。但由于按钮的高度不够,所以不明显。尽管标题插图和内容插图的默认值为零,但标题似乎无法与底部齐平。对我来说,它看起来大约是 5 像素。我用较小的字体进行了测试,以确保这是正确的。

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