Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Way To Move UIButton Between Two Points?

Trying to make a small tapping game, where you have a grid of squares and need to tap them in different orders. Occasionally these squares will swap places with each other.

I figure that I will need to put the locations of each square into an array. Then when it is time to move, go from the current location to a one selected at random from the array, and then deleting that location in the array so I don't get multiple buttons in the same place.

Unfortunately I can't even get the UIButtons to move, let alone interpolate between two positions.

Currently this will move a button:

-(IBAction)button:(id)sender
{
    button.center = CGPointMake(200, 200);
}

But I don't want it to work like that, I want it to work something like this and it doesn't work:

if (allButtonsPressed == YES)
{
    button.center = CGPointMake(200, 200);
}

It won't even move if placed like this:

-(void)viewDidLoad
{
    [super viewDidLoad];
    button.center = CGPointMake(200, 200);
}

For clarity, the button is added through Interface Builder, and all these situations work when doing other things, so I'm guessing UIButtons need to moved/animated in specific ways?

like image 848
William Robinson Avatar asked Jan 27 '26 03:01

William Robinson


1 Answers

viewDidLoad occurs before the view is visible so it will move just not animated. You could try putting it in the viewDidAppear method.

You can wrap things in UIView animation blocks like so if you want them to animate instead of blink into position.

[UIView animateWithDuration:0.5 animations:^{
    button.center = CGPointMake(200.0, 200.0);
}];

Since you're using interface builder I'm assuming your using properties to keep track of the buttons. This can work if you're only using a few set buttons but I'd expect in a game those will change so you may want to move to code or atleast use IBOutletCollections to keep track of the buttons.

Swift 3.0

UIView.animate(withDuration: 0.5) { [weak self] in
    self?.button.center = CGPoint(x: 200, y: 200)
}
like image 151
Ryan Poolos Avatar answered Jan 28 '26 20:01

Ryan Poolos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!