效果圖
本demo實現的是collection cell長按出現操作按鈕並且cell有搖晃的效果,點擊取消,隱藏操作按鈕,動畫停止。
實現
用Masonry佈局和自定義的delegate方法實現
- 初始化collectionView和三個操作按鈕,用masonry佈局,三個按鈕位置在view的下邊,看不到即可;
collectionView自定義collectionViewCell,自定義delegate方法;
@protocol MFCollectionCellDelegate <NSObject> @required @optional - (void)requestCellWithIndexPath:(NSIndexPath *)indexPath gesture:(UILongPressGestureRecognizer *)gesture; @end
給collectionViewCell添加長按手勢,在手勢的觸發方法中讓代理實現代理方法;
if (self.cellDelegate && [self.cellDelegate respondsToSelector:@selector(requestCellWithIndexPath:gesture:)]) { [self.cellDelegate requestCellWithIndexPath:self.indexPath gesture:gesture]; }
在viewController中定義一個BOOL類型的屬性,紀錄collectionView的編輯狀態,在cell的dataSource方法中,通過編輯狀態設置是否有搖晃動畫;
if (self.edit) { [self shakeCell:cell]; }else { //還原 cell.transform = CGAffineTransformIdentity; }
/** 抖動動畫 */ - (void)shakeCell:(CollectionViewCell *)cell { [UIView animateWithDuration:0.1 delay:0 options:0 animations:^{ cell.transform=CGAffineTransformMakeRotation(-0.02); } completion:^(BOOL finished) { [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction animations:^{ cell.transform=CGAffineTransformMakeRotation(0.02); } completion:nil]; }]; }
設置controller爲cell的代理,實現代理方法,在代理方法中,更新三個操作按鈕的frame(因爲初始化三個按鈕時都是參照第取消按鈕設置的,因此只用更新取消按鈕的frame即可),更新編輯狀態,reload collectionView;
if (gesture.state == UIGestureRecognizerStateBegan) { self.editSelectedIndexPath = indexPath; self.edit = YES; [self.collectionView reloadData]; WEAKSELF [UIView animateWithDuration:5.0 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ [self.cancelBtn mas_updateConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(weakSelf.view.mas_bottom); }]; } completion:nil]; }
點擊取消按鈕時觸發的方法中,實現更換編輯裝套,更新collectionView,更新取消按鈕的frame;
self.edit = NO; [self.collectionView reloadData]; WEAKSELF [UIView animateWithDuration:5.0 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{ [self.cancelBtn mas_updateConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(weakSelf.view).offset(60); }]; } completion:nil];