玩轉iOS開發:iOS 11 新特性《UICollectionView的拖放》

CainLuo發表於2017-11-29

文章分享至我的個人技術部落格: https://cainluo.github.io/15102983446918.html


還記得在WWDC 2017的時候, 蘋果爸爸展示的拖放功能是多麼的牛逼, 實現了可誇應用的資料分享.

如果你有看過之前的玩轉iOS開發:iOS 11 新特性《UIKit新特性的基本認識》, 那麼你應該有一個基礎的認識, 如果沒有也沒關係, 因為你正在看著這篇文章.

這裡我們會用一個針對iPad Pro 10.5英寸的小專案進行演示.

轉載宣告:如需要轉載該文章, 請聯絡作者, 並且註明出處, 以及不能擅自修改本文.

工程的配置

這裡我打算使用Storyboard來作為主開發的工具, 為了省下過多的佈局程式碼.

1

這是模仿一個顧客去買水果的場景, 這裡面的佈局也不算難, 主要邏輯:

  • 主容器控制器嵌入兩個比較小的檢視控制器, 通過ListController分別管理.
  • ListController主要是顯示一個UICollectionView, 而我們拖放也是在ListController裡實現的.

簡單的寫了一下資料模型, 並且控制一下對應的資料來源, 我們就可以看到簡單的介面了:

2

配置拖放的功能

配置UICollectionView其實是非常容易的, 我們只需要將一個宣告UICollectionViewDragDelegate代理的例項賦值給UICollectionView, 然後再實現一個方法就可以了.

接下來這裡, 我們設定一下拖放的代理, 並且實現必要的拖放代理方法:

    self.collectionView.dragDelegate = self;
    self.collectionView.dropDelegate = self;
複製程式碼
#pragma mark - Collection View Drag Delegate
- (NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView
             itemsForBeginningDragSession:(id<UIDragSession>)session
                              atIndexPath:(NSIndexPath *)indexPath {
    
    NSItemProvider *itemProvider = [[NSItemProvider alloc] init];
    
    UIDragItem *item = [[UIDragItem alloc] initWithItemProvider:itemProvider];
    
    return @[item];
}
複製程式碼

這樣子我們就可以看到長按CollectionView時會有長按拖放效果了:

3

配置拖放的"放"效果

拖放效果有了, 但問題來了, 當我們拖放到另一個UICollectionView鬆手時, 會發現並不能將資料拖放過去, 其實是我們並沒有配置UICollectionViewDropDelegate代理, 這個和剛剛的配置方法一樣, 這裡就不多說了.

首先我們來實現一個方法:

- (BOOL)collectionView:(UICollectionView *)collectionView
  canHandleDropSession:(id<UIDropSession>)session {
  
    return session.localDragSession != nil ? YES : NO;
}
複製程式碼

這個可選方法是在諮詢你會否願意處理拖放, 我們可以通過實現這個方法來限制從同一個應用發起的拖放會話.

這個限制是通過UIDropSession中的localDragSession進行限制, 如果為YES, 則表示接受拖放, 如果為NO, 就表示不接受.

講完這個之後, 我們來看看UICollectionViewDropDelegate唯一一個要實現的方法, 這個方法要有相應, 是根據上面的那個方法是返回YES還是返回NO來判斷的:

- (void)collectionView:(UICollectionView *)collectionView
performDropWithCoordinator:(id<UICollectionViewDropCoordinator>)coordinator {
    
}
複製程式碼

然後我們配置好UICollectionViewDropDelegate的代理物件, 再試試拖放效果, 機會發現拖到隔壁的UICollectionView的右上角會有一個綠色的加好:

4

配置你的意圖

我們在UICollectionView裡拖動一個物件的時候, UICollectionView會諮詢我們的意圖, 然後根據我們不同的配置, 就會做出不同的反應.

這裡我們要分成兩個部分, 第一個部分是一個叫做UIDropOperation:

typedef NS_ENUM(NSUInteger, UIDropOperation) {
    UIDropOperationCancel    = 0,
    UIDropOperationForbidden = 1,
    UIDropOperationCopy      = 2,
    UIDropOperationMove      = 3,
} API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos);
複製程式碼
  • UIDropOperationCancel: 表示取消拖動操作, 如果是使用這個列舉的話, 會導致-dropInteraction:performDrop:這個方法不被呼叫.
  • UIDropOperationForbidden: 表示該操作被禁止, 如果你是使用這個列舉的話, 在拖放時會顯示一個?的圖示, 表示該操作被禁止.
  • UIDropOperationCopy: 表示從資料來源裡賦值對應的資料, 會在-dropInteraction:performDrop:這個方法裡進行處理.
  • UIDropOperationMove: 表示移動資料來源裡對應的資料, 將對應的資料從資料來源裡移動到目標的地方.

第二個部分是UICollectionViewDropIntent:

typedef NS_ENUM(NSInteger, UICollectionViewDropIntent) {

    UICollectionViewDropIntentUnspecified,
    UICollectionViewDropIntentInsertAtDestinationIndexPath,
    UICollectionViewDropIntentInsertIntoDestinationIndexPath,
} API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos, watchos);
複製程式碼
  • UICollectionViewDropIntentUnspecified: 表示操作即將被拖放的檢視, 但這個位置並不會以明確的方式顯示出來
  • UICollectionViewDropIntentInsertAtDestinationIndexPath: 表示被拖放的檢視會模擬最終放置效果, 也就是說會在目標位置離開啟一個空白的地方來模擬最終插入的目標位置.
  • UICollectionViewDropIntentInsertIntoDestinationIndexPath: 表示將拖放的檢視放置對應的索引中, 但這個位置並不會以明確的方式顯示出來

看到這裡, 如果我們要以明確的方式顯示給使用者的話, 我們就要選中其中一種組合, 什麼組合? 看程式碼唄:

- (UICollectionViewDropProposal *)collectionView:(UICollectionView *)collectionView
                            dropSessionDidUpdate:(id<UIDropSession>)session
                        withDestinationIndexPath:(NSIndexPath *)destinationIndexPath {

    return [[UICollectionViewDropProposal alloc] initWithDropOperation:UIDropOperationMove
                                                                intent:UICollectionViewDropIntentInsertAtDestinationIndexPath];
}
複製程式碼

這種組合可以在我們拖放移動檢視的時候有一個顯式的動畫, 並且UIDropOperationMove的選項也更加符合我們的需求.

模型資料的協調者

雖然蘋果爸爸給UICollectionViewUITableView新增的拖放效果很好, 但有一樣東西是做的並不是很好, 這個就是處理我們的模型層, 這個需要我們開發者自己的搗鼓, 我猜在未來蘋果爸爸會在這一塊裡下手, 從而減少我們的開發者的工作, 當然這只是猜測.

根據我們的拖放互動的複雜性, 我們有兩種方案可以採取:

  1. 如果在不同類的兩個檢視之間拖動單個資料, 比如自定義的UIViewUICollectionView, 我們可以通過localObject這個屬性將模型物件附加到UIDragItem中, 當我們收到拖放時, 我們就可以從拖放管理者裡通過localObject裡檢索模型物件.
  2. 如果是在兩個或者是基於多個的集合類檢視拖放一個或者是多個資料(比如UITableViewUITableView, UICollectionViewUICollectionView, UITableViewUICollectionView), 並且需要跟蹤哪些索引路徑會受到影響以及哪些資料被拖動, 那麼在第一個中方案裡是做不到的, 相反, 如果我們建立一個可以跟蹤事物的自定義拖放管理者, 那麼我們就可以實現了, 比如在源檢視, 目標檢視裡拖動單個或者是多個資料, 然後在這個自定義管理者中傳遞這個在拖放操作中使用UIDragSession中的localContext屬性.

我們這裡使用的就是第二種方式.

建立模型資料協調者

既然剛剛我們說了要搗鼓一個管理者, 那我們先想一想這個管理者要做哪一些工作, 才能夠完成這個拖放並且實現模型更新的操作:

  • 拖動的時候可以找到對應的資料來源, 可以進行刪除操作.
  • 儲存被拖動資料來源的索引路徑.
  • 目標資料來源, 當我們拖放資料來源到指定位置的時候可以知道是在哪裡.
  • 找到拖放資料來源將要插入的索引路徑.
  • 拖放專案將被插入的索引路徑
  • 這裡有一個場景要說明, 如果我們只是移動或者是重新排序的話, 我們要利用UICollectionView提供的API, 具體是取決於這個拖動操作是移動還是重新排序, 所以我們這裡要有一個可以諮詢管理者是什麼型別的拖動.
  • 當所有步驟都完成了, 我們就可以更新源集合檢視了.

需求我們有了, 現在就來實現程式碼了, 先建立一個索引管理者:

ListModelCoordinator.h

- (instancetype)initWithSource:(ListModelType)source;

- (UIDragItem *)dragItemForIndexPath:(NSIndexPath *)indexPath;

- (void)calculateDestinationIndexPaths:(NSIndexPath *)indexPath
                                 count:(NSInteger)count;

@property (nonatomic, assign, getter=isReordering) BOOL reordering;
@property (nonatomic, assign) BOOL dragCompleted;

@property (nonatomic, strong) NSMutableArray *sourceIndexes;

@property (nonatomic, strong) NSMutableArray<NSIndexPath *> *sourceIndexPaths;

@property (nonatomic, strong) NSArray<NSIndexPath *> *destinationIndexPaths;

@property (nonatomic, strong) ListDataModel *listModel;

@property (nonatomic, assign) ListModelType source;
@property (nonatomic, assign) ListModelType destination;
複製程式碼

ListModelCoordinator.m

- (BOOL)isReordering {

    return self.source == self.destination;
}

- (instancetype)initWithSource:(ListModelType)source {
    
    self = [super init];
    
    if (self) {
        
        self.source = source;
    }
    
    return self;
}

- (NSMutableArray<NSIndexPath *> *)sourceIndexPaths {
    
    if (!_sourceIndexPaths) {
        
        _sourceIndexPaths = [NSMutableArray array];
    }
    
    return _sourceIndexPaths;
}

- (NSMutableArray *)sourceIndexes {
    
    if (!_sourceIndexes) {
        
        _sourceIndexes = [NSMutableArray array];
        
        [_sourceIndexPaths enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [_sourceIndexes addObject:@(obj.item)];
        }];
    }
    
    return _sourceIndexes;
}

- (UIDragItem *)dragItemForIndexPath:(NSIndexPath *)indexPath {
    
    [self.sourceIndexPaths addObject:indexPath];
        
    return [[UIDragItem alloc] initWithItemProvider:[[NSItemProvider alloc] init]];
}

- (void)calculateDestinationIndexPaths:(NSIndexPath *)indexPath
                                 count:(NSInteger)count {
    
    NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForItem:indexPath.item
                                                            inSection:0];
    
    NSMutableArray *indexPathArray = [NSMutableArray arrayWithObject:destinationIndexPath];
    
    self.destinationIndexPaths = [indexPathArray copy];
}
複製程式碼

建立完這個索引管理者之後, 我們還要有一個根據這個索引管理者去管理資料來源的ViewModel:

FruitStandViewModel.h

- (instancetype)initFruitStandViewModelWithController:(UIViewController *)controller;

@property (nonatomic, strong, readonly) NSMutableArray *dataSource;

- (ListDataModel *)getDataModelWithIndexPath:(NSIndexPath *)indexPath
                                     context:(ListModelType)context;

- (NSMutableArray *)deleteModelWithIndexes:(NSArray *)indexes
                                   context:(ListModelType)context;

- (void)insertModelWithDataSource:(NSArray *)dataSource
                          context:(ListModelType)contexts
                            index:(NSInteger)index;
複製程式碼

FruitStandViewModel.m

- (instancetype)initFruitStandViewModelWithController:(UIViewController *)controller {
    
    self = [super init];
    
    if (self) {
        self.fruitStandController = (FruitStandController *)controller;
    }
    
    return self;
}

- (ListDataModel *)getDataModelWithIndexPath:(NSIndexPath *)indexPath
                                     context:(ListModelType)context {
    
    NSArray *dataSource = self.dataSource[context];
    
    ListDataModel *model = dataSource[indexPath.row];
    
    return model;
}

- (NSMutableArray *)deleteModelWithIndexes:(NSArray *)indexes
                                   context:(ListModelType)context {
    
    NSMutableArray *array = [NSMutableArray array];
    
    [indexes enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSInteger idex = [obj integerValue];
        
        ListDataModel *dataModel = self.dataSource[context][idex];
        
        [array addObject:dataModel];
    }];
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [self.dataSource[context] removeObject:obj];
    }];
    
    return array;
}

- (void)insertModelWithDataSource:(NSArray *)dataSource
                          context:(ListModelType)context
                            index:(NSInteger)index {
    
    [self.dataSource[context] insertObjects:dataSource
                                  atIndexes:[NSIndexSet indexSetWithIndex:index]];
}

- (NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array];
        
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data"
                                                                                          ofType:@"json"]];
        
        NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:JSONData
                                                                  options:NSJSONReadingMutableLeaves
                                                                    error:nil];
        
        NSArray *data = jsonArray[@"data"];
        
        for (NSArray *dataArray in data) {
            
            [_dataSource addObject:[NSArray yy_modelArrayWithClass:[ListDataModel class]
                                                              json:dataArray]];
        }
    }
    
    return _dataSource;
}
複製程式碼

最後面我們來實現這個UICollectionViewUICollectionViewDragDelegate, UICollectionViewDropDelegate代理方法:

#pragma mark - Collection View Drag Delegate
- (NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView
             itemsForBeginningDragSession:(id<UIDragSession>)session
                              atIndexPath:(NSIndexPath *)indexPath {

    ListModelCoordinator *listModelCoordinator = [[ListModelCoordinator alloc] initWithSource:self.context];

    ListDataModel *dataModel = self.fruitStandViewModel.dataSource[self.context][indexPath.row];
    
    listModelCoordinator.listModel = dataModel;
    
    session.localContext = listModelCoordinator;

    return @[[listModelCoordinator dragItemForIndexPath:indexPath]];
}

- (NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView
              itemsForAddingToDragSession:(id<UIDragSession>)session
                              atIndexPath:(NSIndexPath *)indexPath
                                    point:(CGPoint)point {

    if ([session.localContext class] == [ListModelCoordinator class]) {

        ListModelCoordinator *listModelCoordinator = (ListModelCoordinator *)session.localContext;

        return @[[listModelCoordinator dragItemForIndexPath:indexPath]];
    }

    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView
     dragSessionDidEnd:(id<UIDragSession>)session {

    if ([session.localContext class] == [ListModelCoordinator class]) {

        ListModelCoordinator *listModelCoordinator = (ListModelCoordinator *)session.localContext;

        listModelCoordinator.source        = self.context;
        listModelCoordinator.dragCompleted = YES;

        if (!listModelCoordinator.isReordering) {
            
            [collectionView performBatchUpdates:^{
                
                [collectionView deleteItemsAtIndexPaths:listModelCoordinator.sourceIndexPaths];
                
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}

#pragma mark - Collection View Drop Delegate
- (BOOL)collectionView:(UICollectionView *)collectionView
  canHandleDropSession:(id<UIDropSession>)session {
    
    return session.localDragSession != nil ? YES : NO;
}

- (UICollectionViewDropProposal *)collectionView:(UICollectionView *)collectionView
                            dropSessionDidUpdate:(id<UIDropSession>)session
                        withDestinationIndexPath:(NSIndexPath *)destinationIndexPath {
    
    return [[UICollectionViewDropProposal alloc] initWithDropOperation:UIDropOperationMove
                                                                intent:UICollectionViewDropIntentInsertAtDestinationIndexPath];
}

- (void)collectionView:(UICollectionView *)collectionView
performDropWithCoordinator:(id<UICollectionViewDropCoordinator>)coordinator {

    if (!coordinator.session.localDragSession.localContext) {

        return;
    }

    ListModelCoordinator *listModelCoordinator = (ListModelCoordinator *)coordinator.session.localDragSession.localContext;

    NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForItem:[collectionView numberOfItemsInSection:0]
                                                            inSection:0];

    NSIndexPath *indexPath = coordinator.destinationIndexPath ? : destinationIndexPath;
    
    [listModelCoordinator calculateDestinationIndexPaths:indexPath
                                                   count:coordinator.items.count];

    listModelCoordinator.destination = self.context;

    [self moveItemWithCoordinator:listModelCoordinator
performingDropWithDropCoordinator:coordinator];
}

#pragma mark - Private Method
- (void)moveItemWithCoordinator:(ListModelCoordinator *)listModelCoordinator
performingDropWithDropCoordinator:(id<UICollectionViewDropCoordinator>)coordinator {

    NSArray *destinationIndexPaths = listModelCoordinator.destinationIndexPaths;

    if (listModelCoordinator.destination != self.context || !destinationIndexPaths) {

        return;
    }
    
    NSMutableArray *dataSourceArray = [self.fruitStandViewModel deleteModelWithIndexes:listModelCoordinator.sourceIndexes
                                                                               context:listModelCoordinator.source];

    [coordinator.items enumerateObjectsUsingBlock:^(id<UICollectionViewDropItem>  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        NSIndexPath *sourceIndexPath      = listModelCoordinator.sourceIndexPaths[idx];
        NSIndexPath *destinationIndexPath = destinationIndexPaths[idx];

        [self.collectionView performBatchUpdates:^{

            [self.fruitStandViewModel insertModelWithDataSource:@[dataSourceArray[idx]]
                                                        context:listModelCoordinator.destination
                                                          index:destinationIndexPath.item];
            
            if (listModelCoordinator.isReordering) {
                
                [self.collectionView moveItemAtIndexPath:sourceIndexPath
                                             toIndexPath:destinationIndexPath];

            } else {

                [self.collectionView insertItemsAtIndexPaths:@[destinationIndexPath]];
            }

        } completion:^(BOOL finished) {

        }];

        [coordinator dropItem:obj.dragItem
            toItemAtIndexPath:destinationIndexPath];

    }];

    listModelCoordinator.dragCompleted = YES;
}
複製程式碼

這裡面的用法和之前UITableView的用法有些類似, 但由於是跨檢視的原因會有一些差異.

而且這裡只是作為一個演示的Demo, 寫的時候沒有考慮到

最終的效果:

5

6

工程

https://github.com/CainRun/iOS-11-Characteristic/tree/master/4.DragDrop


最後

碼字很費腦, 看官賞點飯錢可好

微信

支付寶

相關文章