简体   繁体   中英

how to drag a UIButton Scrollview to UIView in iOS

i want to drag a button UIScrollView to another UIView using UIPanGesture . These both views are child of Xib View. I have already tried to create a copy of UIButtonView but im not able to move this smoothly.

Here is some code which i am implementing:

-(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];


        }



}

Please solve this as soon as possible..

try this,

In 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];

And action method is like,

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

Hope this will help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM