Changing screen position of UIView/UIControl upon tapping it

26,790

Solution 1

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];
 }

Solution 2

CGRectOffset(rect, dx, dy)

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

Share:
26,790
James Dunay
Author by

James Dunay

Flash Developer / Objective C

Updated on October 10, 2020

Comments

  • James Dunay
    James Dunay over 3 years

    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{
    
        ???
    }