Search code examples
iosuiviewcalayerkey-value-observinguimotion

Simply display the values of UIInterpolatingMotionEffect?


Here's a puzzle, imagine a typical UIInterpolatingMotionEffect ,,,

UIInterpolatingMotionEffect *horizontalMotionEffect =
  [[UIInterpolatingMotionEffect alloc]
    initWithKeyPath:@" .. some property .."
     type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
horizontalMotionEffect.minimumRelativeValue = @(-50);
horizontalMotionEffect.maximumRelativeValue = @(50);
[someView addMotionEffect:horizontalMotionEffect];

Normally, you have to put in a property in line 3 there -- say, the center.x

But - what if I (very simply) want to see the value of the UIInterpolatingMotionEffect?

(Or I might use it for some other purpose, say.)

Do I actually have to subclass CALayer and make a new animatable property?!

It seems incredibly complicated to just access the value. The only trick I could think of was just make an invisible view, set it to the center, and access the value! Seems silly though.

Any ideas?


Solution

  • You can subclass UIInterpolatingMotionEffect and hook into the method -(NSDictionary *)keyPathsAndRelativeValuesForViewerOffset:(UIOffset)viewerOffset to log either viewerOffset to get the normalized values or look into the dictionary that the super implementation returns to get the interpolated values between your min and max.

    UILogInterpolatingMotionEffect.h

    @interface UILogInterpolatingMotionEffect : UIInterpolatingMotionEffect
    
    @end
    

    UILogInterpolatingMotionEffect.m

    @implementation UILogInterpolatingMotionEffect
    
    -(NSDictionary *)keyPathsAndRelativeValuesForViewerOffset:(UIOffset)viewerOffset
    {
        NSDictionary *superDictionary = [super keyPathsAndRelativeValuesForViewerOffset:viewerOffset)];
        NSLog(@"%@, %@", NSStringFromUIOffset(viewerOffset), superDictionary);
        return superDictionary;
    }
    
    @end
    

    PS: If you are only interested in the viewerOffset, you can even subclass UIMotionEffect. See also the UIMotionEffect class reference.