RCIX
RCIX

Reputation: 39467

UIButton moves when pressed

I am trying to make a UIButton that grows when pressed. Currently i have the following code in my button's down event (courtesy of Tim's answer):

#define button_grow_amount 1.2
CGRect currentFrame = button.frame;
CGRect newFrame = CGRectMake(currentFrame.origin.x - currentFrame.size.width / button_grow_amount,
                                 currentFrame.origin.y - currentFrame.size.height / button_grow_amount,
                                 currentFrame.size.width * button_grow_amount,
                                 currentFrame.size.height * button_grow_amount);
button.frame = newFrame;

However when run this makes my button move up and to the left every time it's pressed. Any ideas?

Upvotes: 1

Views: 473

Answers (2)

Daniel Dickison
Daniel Dickison

Reputation: 21882

You can use CGRectInset:

CGFloat dx = currentFrame.size.width * (button_grow_amount - 1);
CGFloat dy = currentFrame.size.height * (button_grow_amount - 1);
newFrame = CGRectInset(currentFrame, -dx, -dy);

Upvotes: 4

Andrew Johnson
Andrew Johnson

Reputation: 13286

You need some parentheses in there I bet. Remember that division happens before addition/subtraction.

Also, the first two parameters of CGRectMake dictate where on the screen the button is, and the second two indicate the size. So if you just want to change the button size, only set the last two params.

#define button_grow_amount 1.2
CGRect currentFrame = button.frame;
CGRect newFrame = CGRectMake((currentFrame.origin.x - currentFrame.size.width) / button_grow_amount,
                             (currentFrame.origin.y - currentFrame.size.height) / button_grow_amount,
                             currentFrame.size.width * button_grow_amount,
                             currentFrame.size.height * button_grow_amount);

button.frame = newFrame;

Upvotes: 1

Related Questions