DavidNg
DavidNg

Reputation: 2836

iOS SDK: Moving the button into the center of screen by code

I want to move a button to the center of the screen by code. I saw somewhere it is just few lines of code, but could not find them.

Upvotes: 9

Views: 15529

Answers (6)

Darius Miliauskas
Darius Miliauskas

Reputation: 3524

Here is more simple approach:

yourButton.center = self.view.center;

Upvotes: 2

Sumit Kumar
Sumit Kumar

Reputation: 1

bntTimeEtrySave.Frame =new CoreGraphics.CGRect (
    this.View.Center.X-((bntTimeEtrySave.Bounds.Size.Width)/2),
    bntTimeEtrySave.Frame.Y,bntTimeEtrySave.Bounds.Size.Width,
    bntTimeEtrySave.Bounds.Size.Height);

Upvotes: 0

NamPham
NamPham

Reputation: 243

There are some ways to do it without writing any code. If you you want to try to place the button into the centre of screen by using interface settings, you can view my clip.

Upvotes: 0

Matt Wilding
Matt Wilding

Reputation: 20153

This centers the button in its superview:

CGRect bounds = button.superview.bounds;
button.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

Upvotes: 23

rooster117
rooster117

Reputation: 5552

This should do it:

yourButton.frame = CGRectMake(self.view.frame.size.width/2 - yourButton.frame.size.width/2, self.view.frame.size.height/2 - yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height);

Upvotes: 15

Bruno Koga
Bruno Koga

Reputation: 3874

Both rooster117 and DavidNg answers seem correct. Just to add one more "option" to you, if you want to do this animated, you should do:

NSTimeInterval seconds = 1.0;
[UIView animateWithDuration:seconds animations:^{
    //here you should write any reframing/repositioning code
}];

Upvotes: 1

Related Questions