如何将UIButton Scrollview拖动到iOS中的UIView

时间:2016-05-31 07:32:44

标签: ios objective-c uipangesturerecognizer

我想使用UIScrollView将按钮UIPanGesture拖到另一个UIView。这两个视图都是Xib View的子视图。我已经尝试创建UIButtonView的副本,但我无法顺利移动。

以下是我正在实施的一些代码:

-(void) PanGestureFunc :(UIPanGestureRecognizer *) recognizer
{
     CGRect originOnScreen = [recognizer.view convertRect:self.view.bounds toView:nil];





     if(recognizer.state == UIGestureRecognizerStateBegan)
       {

           if([[recognizer.view superview].subviews containsObject:recognizer.view])
             {
                 btn = (UIButton *)recognizer.view;
                 btn.tag = [recognizer.view tag];

                 [recognizer.view removeFromSuperview];
                 [self.view addSubview:btn];

                  float pointX = originOnScreen.origin.x + btn.frame.size.width/2;
                  float pointY = originOnScreen.origin.y + btn.frame.size.height/2;

                 [btn setCenter:CGPointMake(pointX, pointY)];
              }


             CGPoint translation = [recognizer translationInView:self.view];
             btn.center = CGPointMake(btn.center.x + translation.x,
                             btn.center.y + translation.y);

            [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];


        }



}

请尽快解决此问题。

1 个答案:

答案 0 :(得分:1)

试试这个,

Viewdidload

  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(20, 20, 50, 30);
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragOutside];
[button setBackgroundColor:[UIColor orangeColor]];


[self.view addSubview:button];

动作方法就像,

 - (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
UIControl *control = sender;

UITouch *t = [[event allTouches] anyObject];
CGPoint pPrev = [t previousLocationInView:control];
CGPoint p = [t locationInView:control];

CGPoint center = control.center;
center.x += p.x - pPrev.x;
center.y += p.y - pPrev.y;
control.center = center;
}

希望这会有所帮助:)