長按桌面圖示時那個左右搖晃的動畫,是 iOS 相當有辨識度的細節。用 CAKeyframeAnimation 就能重現,重點是讓旋轉角度在負值與正值之間來回跳。
#import "LHViewController.h"
#define angelToRandian(x) ((x)/180.0*M_PI)
@interface LHViewController ()
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation LHViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *longPress =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.imageView addGestureRecognizer:longPress];
}
- (void)longPress:(UILongPressGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"transform.rotation";
anim.values = @[@(angelToRandian(-7)),
@(angelToRandian(7)),
@(angelToRandian(-7))];
anim.repeatCount = MAXFLOAT; // 無限次
anim.duration = 0.2;
[self.imageView.layer addAnimation:anim forKey:nil];
self.btn.hidden = NO; // 同步顯示刪除按鈕
}
}
- (IBAction)delete:(id)sender {
[self.imageView removeFromSuperview];
[self.btn removeFromSuperview];
}
@end
幾個可以微調的地方:values 陣列只有三個關鍵幀(-7、7、-7),所以擺動頻率由 duration 決定,0.2 秒大致接近系統的節奏;把角度調大會更誇張,調小則更細微。若想讓搖晃看起來更自然,可以補上 timingFunctions 指定 ease-in/ease-out。
另外要注意,長按手勢只在 state 為 Began 時啟動動畫一次,因此手指不放開也不會重複觸發;這裡刻意不處理其他狀態,避免動畫被反覆重啟。若要完整模仿 iOS 行為,還可以在動畫開始時同步讓圖示進入「可編輯模式」,例如讓所有圖示一起搖晃並顯示關閉按鈕。