貓貓學iOS之ipad開發Popover的基本使用
一:
二:注意
對於方法[UIPopoverController dealloc] reached while popover is still visible.
當popover還在顯示的時候,它就掛了
不允許popover還在顯示的時候掛掉
popover必須在消失的時候掛掉
三:核心代碼
- (IBAction)popMenu:(id)item { // 0.內容 MenuViewController *menu = [[MenuViewController alloc] init]; // 1.建立一個UIPopover UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]]; // 2.設定尺寸// popover.popoverContentSize = CGSizeMake(320, 44 * 5); // 3.從哪裡顯示出來 --> 指向item [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; self.popover = popover;}
四:全部代碼展示ViewController
#import ViewController.h#import MenuViewController.h@interface ViewController ()- (IBAction)popMenu:(id)item;@property (nonatomic, strong) UIPopoverController *popover;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad];}// -[UIPopoverController dealloc] reached while popover is still visible.// 當popover還在顯示的時候,它就掛了// 不允許popover還在顯示的時候掛掉// popover必須在消失的時候掛掉/** * 彈出Popover菜單 */- (IBAction)popMenu:(id)item { // 0.內容 MenuViewController *menu = [[MenuViewController alloc] init]; // 1.建立一個UIPopover UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]]; // 2.設定尺寸// popover.popoverContentSize = CGSizeMake(320, 44 * 5); // 3.從哪裡顯示出來 --> 指向item [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; self.popover = popover;}@end
MenuViewController
#import MenuViewController.h@interface MenuViewController ()@property (nonatomic, strong) NSArray *titles;@end@implementation MenuViewController- (void)viewDidLoad { [super viewDidLoad]; self.titles = @[@設定, @清除緩衝, @退出, @基本資料]; self.title = @菜單; self.view.backgroundColor = [UIColor blueColor]; CGFloat w = 320; CGFloat h = self.titles.count * 44; self.preferredContentSize = CGSizeMake(w, h);// self.contentSizeForViewInPopover = CGSizeMake(w, h);}#pragma mark - Table view data source- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.titles.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *ID = @cell; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } cell.textLabel.text = self.titles[indexPath.row]; return cell;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UIViewController *vc = [[UIViewController alloc] init]; vc.view.backgroundColor = [UIColor redColor]; [self.navigationController pushViewController:vc animated:YES];}@end