search

Home  >  Q&A  >  body text

ios - 当UIView正在做动画时,如何获取UIView的frame?

当UIView正在做动画时,如何获取UIView的frame?

PHPzPHPz2892 days ago300

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-18 09:19:43

    Use the presentationLayer attribute to get the latest frame.
    Sample:

    - (IBAction)move {
        CGRect destRect = self.frame;
        destRect.origin.x = 300 - destRect.origin.x;
    
        __block BOOL animationComplete = FALSE;
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
        [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationCurveEaseInOut
                         animations:^{
                             [self setFrame:destRect];
                         }
                         completion:^(BOOL finished) {
                             animationComplete = YES;
                             [[UIApplication sharedApplication] endIgnoringInteractionEvents];
                         }];
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, (unsigned long)NULL), ^{
            while (!animationComplete) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    CALayer *layer = self.layer.presentationLayer;
                    CGRect frame = [layer frame];
                    CGPoint point = [layer position];
                    float currentTranslation = [[layer valueForKeyPath:@"transform.translation.x"] floatValue];
                    NSLog(@"%.1f : %.1f : %.1f : %.1f : %.1f : %.1f",frame.origin.x, currentTranslation, frame.origin.x, layer.bounds.origin.x, layer.position.x, point.x);
                });
            }
        });
    }

    Reference link

    Supplement:
    The principle of the above sample is that after the animation starts, the latest frame is continuously obtained through the presentationLayer in the low-priority sub-thread until the animation ends. Of course, you can use NSTimer to achieve this.

    reply
    0
  • Cancelreply