コンテンツへスキップ →

UIPopoverControllerでTableViewを表示させる

iPadで使えるボタンを押すとふわっと吹き出しが出てくるUIPopoverControllerの実装方法です。UIPopoverControllerの中身は別Viewで用意しておく必要がありますが、xibを作らずにプログラムだけで実装可能です。今回はテーブルビューを表示するようにしています。

読み込み先のテーブルビューを作る

先に、ポップアップの中に表示させるテーブルビューの準備から。

DLViewController.h

#import <UIKit/UIKit.h>
@interface DLViewController : UITableViewController
@end

DLViewController.m

#import "DLViewController.h"

@interface DLViewController ()

@end

@implementation DLViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

//以下テーブル表示メソッド
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return 10;
}

//セルの高さ
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *SimpleTableIdentifier= @"SimpleTableIdentifier";
	UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];

    if(cell==nil){
        cell=[[UITableViewCell alloc]
              initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier];
    }

    cell.textLabel.text=@"a";

    return cell;
}

//セルがクリックされた時の処理
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

そして、ポップアップを呼び出すView。

testView.h

@interface testView : UIViewController<UIPopoverControllerDelegate>{
   UIPopoverController *popoverController;
   IBOutlet UIButton *popbutton;
}
- (IBAction) tapAction:(id)sender;

popbuttonはUIButtonですが、このボタンがタップされたときにポップオーバーを表示させます。ですので、あらかじめボタンとtapAction、popbuttonもそれぞれ紐付けておいてください。

testView.m

#import "DLViewController.h"

- (IBAction) tapAction:(id)sender
{
    // 表示するViewController
    DLViewController *svc = [[DLViewController alloc] init];
    popoverController = [[UIPopoverController alloc] initWithContentViewController:svc];
    popoverController.delegate = self;

    // Popoverを表示する
    [popoverController presentPopoverFromRect:popbutton.bounds
                                       inView:popbutton permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
}

というわけで、これを実行するとこのようにポップアップが表示されました。

[sc name=”ios”][sc name=”engeneer”]

SPONSER

SHARE

YouTube

Mail Magazine

毎週1回ブログの更新情報をお届けします。登録はこちらから。無料メルマガ特典として「個人開発の教科書<心得編>」をご覧いただけます。

PROFILE

入江 慎吾
個人開発クリエイター。MENTAなどをはじめ、これまでに30個ほどのサービスやアプリをつくりました。電子書籍「個人開発の教科書」を出版しました。コンサル、開発のご依頼はこちらまで。 (詳しいプロフィール)

カテゴリー: 開発奮闘記