如何以编程方式对齐iOS应用程序中的按钮?

iHa*_*rMe 13 iphone objective-c ios

我如何能够对齐普通的UIButton,例如.以编程方式在顶部,底部或中间?

The*_*ger 54

你必须设置UIButton自己的框架.

水平对齐

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

垂直对齐

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

左上方

[button setFrame:CGRectMake(0.0, 0.0, yourButtonWidth, yourButtonheight)]; 
Run Code Online (Sandbox Code Playgroud)

右上

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

左下方

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

BOTTOM RIGHT

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

自我中心

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

  • 虽然这个答案是正确的,但是当您将框架置于高度或宽度为15像素的不均匀值时,可能会遇到图形问题.帧可能从某个半像素开始,模糊了视图.要解决这个问题,一个解决方案可能是在设置中心后使用`button.frame = CGRectIntegral(button.frame);`来纠正帧. (4认同)

Vim*_*lan 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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 但是,这并不能补偿按钮的大小.例如,在第一行,您的按钮将部分不在视图中. (3认同)
  • 实际上这个人想要对齐按钮(顶部,底部或中间)而不是设置框架,因此我给出了答案 (2认同)

woz*_*woz 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;

等等.