UIButton 没有设置居中

UIButton doesn't set center

我在故事板上手动添加了一个按钮。我想当屏幕加载时,此按钮将其中心设置为我给它的坐标

-(void)viewWillLayoutSubviews{
    NSLog(@"Will Layout");
    CGPoint buttonPoint;
    buttonPoint.y = self.view.frame.size.height - 50;
    buttonPoint.x = self.view.frame.size.width /2;

    [menuButton setCenter:buttonPoint];
}

但是没有任何变化,按钮仍然停留在我第一次拖动它的地方。 我做错了什么?

对于现代的基于 AutoLayout 和旧的遗留 Springs&Struts 的布局管理方法来说都非常简单。

自动布局

您只需设置两个约束,使按钮保持在水平中间和垂直中间减去 50 点。

弹簧 & STRUTS

您将通过在大小检查器中正确设置自动调整大小掩码来确保将按钮设置为居中。然后在代码中,在视图控制器的 viewDidLoad 方法中,您将修复 50 点偏移量。

(有些人可能会建议使用 viewWillLayoutSubviews,但我们现在不要让它复杂化。)

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.button.frame = CGRectMake(self.button.frame.origin.x,
                                   self.button.frame.origin.y - 50,
                                   self.button.frame.size.width,
                                   self.button.frame.size.height);

/// other code....
}