效果图
![UIPopoverPresentationController使用(https://img-blog.csdn.net/20180801112016614?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BvdGF0bzUxMg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
UIPopoverPresentationController
使用说明
1、创建弹窗视图控制器,如:MenuController
2、实例化弹窗视图控制器时,设置其显示大小preferredContentSize
和显示模式modalPresentationStyle
3、根据实例化的弹窗视图控制器获取视图控制器UIPopoverPresentationController
4、设置UIPopoverPresentationController
的相关属性,如:箭头显示方向permittedArrowDirections
、显示视图sourceView
、显示位置sourceRect
、显示时的背景颜色backgroundColor
5、根据需要设置代理delegate
,及实现代理协议UIPopoverPresentationControllerDelegate
方法
6、显示,如:[self presentViewController:self.menuVC animated:YES completion:nil];
7、隐藏,如:[self dismissViewControllerAnimated:YES completion:NULL];
使用注意事项:设置显示位置
sourceRect
和显示视图sourceView
时,通常是根据子视图的来做处理的。如,要显示在按钮button的旁边,则sourceView
为button,且sourceRect
为button的button.bounds
;或sourceView
为button的父视图view,且sourceRect
为buttond在父视图view的位置button.frame
;
代码示例
1、继承UIViewController
创建视图控制器MenuViewController
#import <UIKit/UIKit.h>
@interface MenuViewController : UIViewController
@property (nonatomic, copy) void (^itemClick)(NSInteger index);
@end
#import "MenuViewController.h"
@interface MenuViewController () <UITableViewDelegate, UITableViewDataSource>
@end
@implementation MenuViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
[self.view addSubview:tableView];
tableView.delegate = self;
tableView.dataSource = self;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
tableView.tableFooterView = [UIView new];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
cell.textLabel.text = [NSString stringWithFormat:@"%@", @(indexPath.row)];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (self.itemClick) {
self.itemClick(indexPath.row);
}
}
@end
2、使用