LoginSignup
5
7

More than 5 years have passed since last update.

UICollectionViewCellの編集メニューを表示する

Posted at

やりたいこと

任意のUICollectionViewCellがロングタップされた際に任意の編集メニューを表示する。

こんな感じ↓
EditMenuSample

環境

  • Xcode 7.1
  • iOS 9.1

上記環境以外では試していませんが、おそらくiOS6.0以降なら動作すると思います

方法

UICollectionViewCellの編集メニューを表示するには、まず次の3つのデリゲートメソッドを実装する必要があります。

  1. collectionView:shouldShowMenuForItemAtIndexPath:
  2. collectionView:canPerformAction:forItemAtIndexPath:withSender:
  3. collectionView:performAction:forItemAtIndexPath:withSender:

さらに、各々のメソッド内で編集メニュー表示に関する細かい指定を行う処理を記述する必要があります。

順に説明していきます。

1. collectionView:shouldShowMenuForItemAtIndexPath:

編集メニューを表示するセルをBOOL値を返すことにより指定します。このメソッドでNOが返されたIndexPathのセルについては編集メニューは表示されません。

- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.row < 3 ) {
        return YES;
    }

    return NO;
}

この場合は最初の3つのセル(0〜2)のみ編集メニューが表示されます。

2. collectionView:canPerformAction:forItemAtIndexPath:withSender:

どの編集メニューを表示するかをBOOL値を返すことにより指定します。編集メニューの種類とセレクタとして渡されるアクションメソッドは次の通りです。

メニュー アクションメソッド
カット cut:
コピー copy:
ペースト paste:
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(nonnull SEL)action forItemAtIndexPath:(nonnull NSIndexPath *)indexPath withSender:(nullable id)sender
{
    if ( [NSStringFromSelector(action) isEqualToString:@"copy:"]
        || [NSStringFromSelector(action) isEqualToString:@"paste:"] ) {
        return YES;
    }

    return NO;
}

この場合はコピーペーストのみ編集メニューとして表示されます。

3. collectionView:performAction:forItemAtIndexPath:withSender:

最後に、編集メニューがタップされたときの動作を記述します。

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if ( [NSStringFromSelector(action) isEqualToString:@"copy:"] ) {
        // なんかする
    } else if ( [NSStringFromSelector(action) isEqualToString:@"paste:"] ) {
        // なんかする
    }
}

上記のコードではしていませんが、引数として(当たり前ですが)セルのindexPathが渡されるので、それをもとに何か処理を記述することになると思います。

まとめ

  1. collectionView:shouldShowMenuForItemAtIndexPath: メソッドを実装し、編集メニューを表示するセルを指定
  2. collectionView:canPerformAction:forItemAtIndexPath:withSender: メソッドで表示する編集メニューを内容(カット/コピー/ペーストのいずれか)を指定
  3. collectionView:performAction:forItemAtIndexPath:withSender: メソッドで編集メニュータップ時の処理を記述

今回はデフォルトのUICollectionViewCellをそのまま使用していますが、自作Cellクラスを使用しても同様にして編集メニュー表示を実現できます。

参考文献

今回の記事を執筆するにあたり、Appleの公式ドキュメンドである『Collection View Programming Guide for iOS』の「Showing the Edit Menu for a Cell」の項目を参照しました。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7