I'm well aware this is a simple question. I would like to learn how to move a CGRect/UIButton to a different spot on the screen when the user selects it. Thanks for your help in advance.
- (void)showMeSomeButtons:(CGRect)frame{
button = [[UIButton alloc] initWithFrame:frame];
button.frame = CGRectMake(240, 150, 50, 50);
UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];
[button setBackgroundImage:buttonGraphic forState:UIControlStateNormal];
[button addTarget:self.viewController action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
-(void)buttonClicked{
???
}
I think you need to add a :
in the @selector(buttonClicked:)
statement since IBAction
s expect a single (id)sender
method attribute.
You can do something similar to the code below.
- (void)buttonClicked:(id)sender {
CGRect frame = button.frame;
frame.origin.x = 500; // new x coordinate
frame.origin.y = 500; // new y coordinate
button.frame = frame;
}
If you want to animate it, you can add the beginAnimation block.
- (void)buttonClicked:(id)sender {
CGRect frame = button.frame;
frame.origin.x = 500; // new x coordinate
frame.origin.y = 500; // new y coordinate
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.25];
button.frame = frame;
[UIView commitAnimations];
}
CGRectOffset(rect, dx, dy)
Moves the origin of the rect by the delta X and Y.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With