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]; }
というわけで、これを実行するとこのようにポップアップが表示されました。
効率のいいiOSプログラミング習得法
独学でプログラミングをはじめてもう16年。なかなか勉強が進まない人のために記事を書きました。
フリーランスエンジニアの稼ぎ方
SPONSOR
PROFILE
プロフィール

入江 慎吾
受託開発で年3,000万以上を売り上げるも、受託をやめることを決意 / 自分のサービスで生きていくために挑戦中🔥現在プロダクトの売上は月40万円 / 個人開発コミュニティ「入江開発室」を運営(約300名) / MENTAなど20個以上のプロダクトを開発。
(詳しいプロフィール)
受託開発で年3,000万以上を売り上げるも、受託をやめることを決意 / 自分のサービスで生きていくために挑戦中🔥現在プロダクトの売上は月40万円 / 個人開発コミュニティ「入江開発室」を運営(約300名) / MENTAなど20個以上のプロダクトを開発。
(詳しいプロフィール)
PRODUCT
イリテクで開発したプロダクト
SPONSOR