简体   繁体   中英

UIButton doesn't set center

I have a button I added manually on the storyboard. I would like when the screen loads, to this button sets its center with the coordination I give to it by

-(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];
}

But nothing changes, the button stays still on the place I first dragged it. What am I doing wrong?

It's very simple for both the modern AutoLayout based and old legacy Springs&Struts based layout management approach.

AUTOLAYOUT

You simply set up two constraints that will keep the button in the horizontal middle and in the vertical middle minus 50 points up. 在此处输入图片说明

SPRINGS & STRUTS

You will make sure the button is set to be in the center by setting the autoresizing mask properly in the Size inspector. Then in code, in view controller's viewDidLoad method, you will fix the 50 points offset.

(Some might suggest viewWillLayoutSubviews, but let's not complicate it for now.)

- (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....
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM