项目中首页按钮按照需求需要实现拖拽排序并且记录排序后的布局,下次再进入APP后展示排序后的布局。
功能分析
实现此功能需要实现两个点,第一就是拖拽排序的实现,第二就是存储排序后的布局,针对第一个功能点,拖拽排序:这个可以使用collectionView系统自带的功能来实现,针对第二个功能点,我使用NSUserDefaults
本地存储盛放collectionViewCell
内容的数组。
整体效果如图:
![668737-53f53f5e2a4bb9a7.png](https://i-blog.csdnimg.cn/blog_migrate/bbc862a1789d14d77c63d9c97e41d18c.png)
屏幕快照 2019-01-29 上午11.10.24.png
本地存储的实现
每个cell由背景图片和title组成,NSDictionary *dic1 = @{@"title":@"标题", @"img":@"bgImg"};
每个字典存放两个字段,根据需求,创建相应的字典,NSArray *tempArr = @[dic1,dic2,dic3,dic4,dic5]``[self.homeBtnsArr addObjectsFromArray:tempArr];
将字典放在数组中,便于在collectionView的代理方法中使用,[[NSUserDefaults standardUserDefaults] setObject:self.homeBtnsArr forKey:@"stuHomeBtns"];
将数组做本地储存,在每次进入界面时,先去NSUserDefaults
中查找存放的数组,再去使用。
拖拽移动功能的实现
1、创建collectionView
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-50.0)/4, 85);
flowLayout.minimumLineSpacing = 0.1;
flowLayout.minimumInteritemSpacing = 0.1;
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
collectionView.backgroundColor = [UIColor whiteColor];
collectionView.delegate = self;
collectionView.dataSource = self;
self.collectionView = collectionView;
[self addSubview:collectionView];
[collectionView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(0);
}];
[collectionView registerClass:[HomeSortBtnCell class] forCellWithReuseIdentifier:@"HomeSortBtnCell"];
2、在collectionView上添加长按手势
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
[collectionView addGestureRecognizer:longPress];
3、长按手势响应方法
#pragma mark 长按响应方法
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress {
[self action:longPress];
}
4、处理长按手势
- (void)action:longPress:(UILongPressGestureRecognizer *)longPress {
switch (longPress.state) {
case UIGestureRecognizerStateBegan:
{
//手势开始
//判断手势落点位置是否在row上