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”]
SHARE
PROFILE

入江 慎吾
Webサービスを作るのが大好きです。制作会社10年→フリーランス→受託をやめサービス開発に専念。プログラミングのメンターサービスMENTAは月間流通額約1,300万を突破🚀 YouTubeでは個人開発について語ってます / 「自分のサービスで生きていく」をコンセプトに個人開発オンラインサロン「入江開発室」を運営(詳しいプロフィール)
Webサービスを作るのが大好きです。制作会社10年→フリーランス→受託をやめサービス開発に専念。プログラミングのメンターサービスMENTAは月間流通額約1,300万を突破🚀 YouTubeでは個人開発について語ってます / 「自分のサービスで生きていく」をコンセプトに個人開発オンラインサロン「入江開発室」を運営(詳しいプロフィール)