Bin
Bin

Reputation: 484

how to move the UIButton

i create a UIButton *actionbtn,it's default image is 1.png,and hightlight image is 2.png, i select this button,and move it to any place of the screen.my code is

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint touchMoved = [touch locationInView:self];
    actionbtn.frame = CGRectMake(touchMoved.x-40, touchMoved.y-40, 80, 80);
}

if i clicked the button and move it,it can not be moved,but if i touch the screen,and move on the screen the button can work...

Upvotes: 0

Views: 2480

Answers (3)

zedzhao
zedzhao

Reputation: 517

add an if clause in touchesMoved function.

UITouch *touch = [touches anyObject];    
if( touch.view == button){
     [button.center = [touch locationInView:self.view];
    }

Upvotes: 0

elp
elp

Reputation: 8131

Try this:

http://developer.apple.com/library/ios/#samplecode/MoveMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007315

It's an example with an UIButton that move on screen...

Upvotes: 2

user756245
user756245

Reputation:

The button is moving when you keep touching the screen because you implemented -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;. If you attempted to move the button when simply touching the screen anywhere, place that code in -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;.

Upvotes: 0

Related Questions