0

我正在制作一个应用程序,其中有不同颜色的不同按钮,如果我在特定视图上拖动此颜色按钮,其颜色必须更改为此按钮的颜色,并且颜色按钮应重新定位在其原始位置。我尝试了各种方法,例如开始触摸和结束触摸,但似乎并没有解决我的问题。我还尝试了在各种 uicontrolstate 上触发的自定义方法,但效果不佳。请帮我解决这个问题。

4

3 回答 3

3

我认为您使用 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 是让按钮用手指移动

- (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];
        }
}
于 2012-07-25T13:47:46.937 回答
1

我认为您不需要使用按钮,您可以创建 UIView,为其设置背景颜色,并为其添加平移手势。在 .h 文件中创建一些变量:

UIView *green;
CGRect initialPosition;

在 .m 文件中的 init 方法中添加类似这样的东西

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];
    }
}
于 2012-07-25T13:15:12.533 回答
0

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

于 2012-07-25T13:43:56.567 回答