iOS iPhone中的可拖拽button可以在触摸结束后重新定位到原来的位置。

我正在做一个应用程序,有不同的颜色button,如果我在特定的视图上拖动这个颜色button,它的颜色必须改变为这个button的颜色,颜色button应该重新定位在它的原始位置。 我尝试了各种方法,如触摸开始,触动结束,但似乎并没有解决我的问题。 我也尝试了各种uicontrolstate的定制方法,但它没有工作。 请帮我解决这个问题。

我觉得你用touchesBegan,touchesMoved和touchesEnded可以解决这个问题。

touchesBegan是标记orignPosition。

CGPoint orignPosition; CGColor buttonColor; - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; UIView *touchView = [touch view]; if ([touchView isKindOfClass:[UIButton class]]) { orignPosition = (UIButton *)touchView.center; buttonColor = (UIButton *)touchView.backgroundColor; } } 

touchesMoved是让你的手指button移动

 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; UIView *touchView = [touch view]; CGPoint movedPoint = [touch locationInView:yourMainView]; CGPoint deltaVector = CGPointMake(movedPoint.x - lastTouchPoint.x, movedPoint.y - lastTouchPoint.y); lastTouchPoint = movedPoint; if ([touchView isKindOfClass:[UIButton class]]) { touchView.center = CGPointMake(touchView.center.x + deltaVector.x, touchView.center.y + deltaVector.y); } } 

touchesEnded是判断是否改变你的特殊视图的颜色

 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; UIView *touchView = [touch view]; CGPoint movedPoint = [touch locationInView:scrollView]; if ([touchView isKindOfClass:[UIButton class]]) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; (UIButton *)touchView.center = orignPosition; [UIView commitAnimations]; } if(CGRectContainsPoint(specialView.frame, [touch locationInView:yourMainView])) { [yourMainView setBackgroundColor:buttonColor]; } } 

我认为你不需要使用button,你可以创buildUIView,设置背景颜色,并添加平移手势。 在.h文件中创build一些variables:

 UIView *green; CGRect initialPosition; 

在init文件中的.m文件中添加somethig像这样

 initialPosition = CGRectMake(0, 0, 44, 44); green = [[UIView alloc]initWithFrame:initialPosition]; green.backgroundColor = [UIColor greenColor]; UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(habdlePan:)] [green addGestureRecognizer:green]; [panGesture release]; [self.view addSubview:green]; [green release]; 

HandleTap必须如下所示:

 - (void) habdlePan:(UIPanGestureRecognizer *)panGesture { //Move your button here if(gestureRecognizer.state == UIGestureRecognizerStateEnded) { //All fingers are lifted. //Return btn to init position [UIView beginAnimations:nil context:nil]; green.frame = initialPosition; [UIView commitAnimations]; } } 

我想build议你使用UIImageView而不是UIButton 。 设置[UIImageView userInractionEnabled:YES] 。 这会更好。 您可以使用touchBegin:轻松拖动touchBegin: touchMove:方法。