Subclassing MKAnnotationView and overriding setDragState

后端 未结 3 1883
不知归路
不知归路 2020-12-01 11:25

This is about an iPhone App using MKMapKit:

I created a custom MKAnnotationView for a draggable Annotation. I want to create a custom animation. I set a custom pin i

3条回答
  •  醉梦人生
    2020-12-01 12:10

    I had the pin drag working but was trying to figure out why the pin annimations that occur when you don't override setDragState - no longer work in my implementation. Your question contained my answer .. Thanks!

    Part of the problem with your code is that once you override the setDragState function, per the xcode documentation, you are responsible for updating the dragState variable based on the new state coming in. I would also be a little concerned about your code calling itself (setDragState calling [self setDragState]).

    Here is the code I ended up (with your help) that does all of the lifts, drags and drops as I expect them to occur. Hope this helps you too!

    - (void)setDragState:(MKAnnotationViewDragState)newDragState animated:(BOOL)animated
    {
        if (newDragState == MKAnnotationViewDragStateStarting)
        {
            // lift the pin and set the state to dragging
    
            CGPoint endPoint = CGPointMake(self.center.x,self.center.y-20);
            [UIView animateWithDuration:0.2
                             animations:^{ self.center = endPoint; }
                             completion:^(BOOL finished)
                                 { self.dragState = MKAnnotationViewDragStateDragging; }];
        }
        else if (newDragState == MKAnnotationViewDragStateEnding)
        {
            // save the new location, drop the pin, and set state to none
    
            /* my app specific code to save the new position
            objectObservations[ACTIVE].latitude = pinAnnotation.coordinate.latitude;
            objectObservations[ACTIVE].longitude = pinAnnotation.coordinate.longitude;
            posChanged = TRUE;
            */
    
            CGPoint endPoint = CGPointMake(self.center.x,self.center.y+20);
            [UIView animateWithDuration:0.2
                             animations:^{ self.center = endPoint; }
                             completion:^(BOOL finished)
                                 { self.dragState = MKAnnotationViewDragStateNone; }];
        }
        else if (newDragState == MKAnnotationViewDragStateCanceling)
        {
            // drop the pin and set the state to none
    
            CGPoint endPoint = CGPointMake(self.center.x,self.center.y+20);
            [UIView animateWithDuration:0.2
                             animations:^{ self.center = endPoint; }
                             completion:^(BOOL finished)
                                 { self.dragState = MKAnnotationViewDragStateNone; }];
        }
    }
    

提交回复
热议问题