如何移动UIButton

时间:2011-07-14 13:26:46

标签: ios uibutton touch

我创建了一个UIButton * actionbtn,它的默认图像是1.png,而hightlight图像是2.png,我选择这个按钮,并将它移动到屏幕的任何位置。我的代码是

-(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);
}

如果我点击按钮并移动它,它就无法移动,但如果我触摸屏幕,并在屏幕上移动按钮就可以工作......

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

当您持续触摸屏幕时,按钮正在移动,因为您实施了-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;。如果您只是在任何地方触摸屏幕时尝试移动按钮,请将该代码放在-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

答案 2 :(得分:0)

在touchesMoved函数中添加if子句。

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