13

我将如何能够对齐一个普通的UIButton例如。以编程方式在顶部、底部或中间?

4

5 回答 5

54

你必须为自己设定UIButton框架。

水平对齐

float X_Co = (self.view.frame.size.width - yourButtonWidth)/2;
[button setFrame:CGRectMake(X_Co, yourYposition, yourButtonWidth, yourButtonheight)];

垂直对齐

float Y_Co = (self.view.frame.size.height - yourButtonheight)/2;
[button setFrame:CGRectMake(yourXposition, Y_Co, yourButtonWidth, yourButtonheight)];

左上方

[button setFrame:CGRectMake(0.0, 0.0, yourButtonWidth, yourButtonheight)]; 

右上

float X_Co = self.view.frame.size.width - yourButtonWidth;
[button setFrame:CGRectMake(X_Co, 0.0, yourButtonWidth, yourButtonheight)];

左下方

float Y_Co = self.view.frame.size.height - yourButtonheight;
[button setFrame:CGRectMake(0.0, Y_Co, yourButtonWidth, yourButtonheight)];

右下角

float X_Co = self.view.frame.size.width - yourButtonWidth;
float Y_Co = self.view.frame.size.height - yourButtonheight;
[button setFrame:CGRectMake(X_Co, Y_Co, yourButtonWidth, yourButtonheight)];

自我观的中心

button.center = self.view.center;
OR
float X_Co = (self.view.frame.size.width - yourButtonWidth)/2;
float Y_Co = (self.view.frame.size.height - yourButtonheight)/2;
[button setFrame:CGRectMake(X_Co, Y_Co, yourButtonWidth, yourButtonheight)];
于 2012-09-12T12:27:31.697 回答
20

您可以设置按钮的中心以相应地放置它

yourButton.center = CGPointMake(0.0, 0.0);// for topleft

yourButton.center = CGPointMake(160.0, 240.0);// for center

yourButton.center = CGPointMake(320.0, 480.0);// for bottomright

希望这可以帮助

于 2012-09-12T12:25:32.297 回答
5

设置子视图位置的唯一方法是手动。您可以像这样设置框架,例如:

在此处输入图像描述

或者改变原点,像这样,例如:

view.frame.origin.x = INT_VALUE;

获得某种对齐的唯一方法是用self.view.frame. 如果要将对象与屏幕中间水平对齐,请使用以下命令:

view.frame.origin.x = self.view.frame.size.width / 2

如果您想以 44 像素的边距将某些内容与顶部对齐,请使用以下命令:

view.frame.origin.y = self.view.frame.origin.y = (view.frame.size.height / 2) + 44;

等等。

于 2012-09-12T12:22:02.083 回答
3

你应该设置它的框架。

就像是

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(320, 120, 35, 10)];

或者

button.frame = CGRectMake(320, 120, 35, 10);

请记住,前两个值分别是视图的宽度和高度(在 X 和 Y 中的位置),第二个值是按钮本身的宽度和高度。

所以,如果你想在顶部有一个按钮,你应该输入

button.frame = CGRectMake(0, 0, 35, 10);

中间

button.frame = CGRectMake(160, 240, 35, 10);

底部

button.frame = CGRectMake(320, 480, 35, 10);
于 2012-09-12T12:21:54.470 回答
0

@TheTiger 的好建议!我把这个逻辑放在一个快速的类中:

https://github.com/iurims/iSLibs/blob/master/ISPositionCalculator.swift

于 2014-11-13T02:26:22.380 回答