LoginSignup
14
16

More than 5 years have passed since last update.

UITableViewControllerを用いたViewの下部にUIToolBarを表示する

Last updated at Posted at 2013-05-14

UITableViewControllerで、テーブルのセルを長押しした時に、画面の下部からツールバーが「にゅる」っとでてくる感じでメニューを表示できるようなものを作ってみたメモです。
storyboardでUIToolBarをつけると、セルの下にくっついてしまって意図した表示にならなかったので作ってみた次第です。

https://github.com/myaaaaa-chan/TableViewAndToolBar

非表示にする時は、ツールバーを画面外に移動させる感じで。

TVTableViewController.m
    // にゅるっと表示/非表示になるようにアニメーションを設定する
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.4];

    //Create a rectangle for the toolbar
    int posisitonHeight = 0;
    if (isVisible == YES) {
        posisitonHeight = rootViewHeight - toolbarHeight;
    }
    else {
        posisitonHeight = rootViewHeight + toolbarHeight;
    }
    CGRect rectArea = CGRectMake(0, posisitonHeight, rootViewWidth, toolbarHeight);

    //Reposition and resize the receiver
    [menuToolBar setFrame:rectArea];

    [UIView commitAnimations];

viewDidLoadで長押しのジェスチャーを登録。
handleLongPressGesture:でツールバーを表示しています。長押しされたセルが特定できるので、表示しているデータをメニューのアクションの対象のデータとして保持しておくといいと思います。

TVTableViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // テーブルビューにロングクリックジェスチャーを設定
    UIGestureRecognizer *longClickGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressGesture:)];
    [self.tableView addGestureRecognizer:longClickGesture];

    // ダミーアイテム
    tableItemArray = [[NSArray alloc]initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];

    [self.tableView reloadData];
}

// テーブルビュー長押しジェスチャーハンドル
- (void) handleLongPressGesture:(UILongPressGestureRecognizer*) sender
{
    // 長押しを開始
    if (sender.state == UIGestureRecognizerStateBegan) {

        // 長押しされたセルを特定
        CGPoint p = [sender locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];

        if (indexPath == nil) {
            NSLog(@"long press on table view but not on a row");
        }
        else {
            // メニューツールバーを表示
            [self showMenuToolBar];
        }
    }
}

プラスで長押しされたセルの色を変えたりするとよりわかりやすいと思います。
サンプルではUIToolBarを毎回作り直していますが、セルによってメニューの内容が変わることを意図してそうしています。内容が変わらないのであれば、作り直す必要はないと思います。

14
16
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
14
16