iOS 7 提供了 UIInterpolatingMotionEffect,可以讓畫面中的視圖隨裝置傾斜而產生立體的位移感。做法很簡單:分別針對水平與垂直軸建立兩個 motion effect,再掛到目標視圖上即可。
- (void)registerEffectForView:(UIView *)aView depth:(CGFloat)depth;
{
UIInterpolatingMotionEffect *effectX;
UIInterpolatingMotionEffect *effectY;
effectX = [[UIInterpolatingMotionEffect alloc]
initWithKeyPath:@"center.x"
type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
effectY = [[UIInterpolatingMotionEffect alloc]
initWithKeyPath:@"center.y"
type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
effectX.maximumRelativeValue = @(depth);
effectX.minimumRelativeValue = @(-depth);
effectY.maximumRelativeValue = @(depth);
effectY.minimumRelativeValue = @(-depth);
[aView addMotionEffect:effectX];
[aView addMotionEffect:effectY];
}
其中 depth 參數決定位移幅度,數值越大,視圖隨傾斜移動的範圍就越明顯。