我该如何通过编程来使一个普通的UIButton在顶部、底部或中间对齐?
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)];
self.view的中心点
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)];
button.frame = CGRectIntegral( button.frame );
来校正框架。 - Wolfgang SchreursCGRectIntegral();
将其变成"整数"值,例如7.5将变成7.0。当您创建一个宽度为73、高度为25的按钮并使用center
方法对齐时,您可以自己测试模糊的图像。 - Wolfgang Schreurs您可以设置按钮的中心以相应地放置它
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
希望这可以帮到你。
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);
非常棒的@TheTiger的技巧! 我把这个逻辑放在了一个Swift类中:
https://github.com/iurims/iSLibs/blob/master/ISPositionCalculator.swift