Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing screen position of UIView/UIControl upon tapping it

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{

    ???
}
like image 945
James Dunay Avatar asked Dec 07 '22 23:12

James Dunay


2 Answers

I think you need to add a : in the @selector(buttonClicked:) statement since IBActions 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];
 }
like image 79
Gianz Avatar answered Feb 08 '23 23:02

Gianz


CGRectOffset(rect, dx, dy)

Moves the origin of the rect by the delta X and Y.

like image 39
user2083364 Avatar answered Feb 09 '23 00:02

user2083364