IOS对于带有箭头的弹出框有一个专门的控件,叫做UIPopoverController。本文将讲解该控件的封装(封装为UIView)与使用。
成品图:
1. 首先来说说UIPopoverController包含了那些常用的方法
大家可以将这个控件看做一个带箭头的弹出框,需要放什么内容,需要自己进行添加,然后放到弹出里面。如果需要一个列表,那么需要放封装了UITableView的UIViewController到里面。系统也给我们提供了一个初始化方法:
- (id)initWithContentViewController:(UIViewController *)viewController;
从这个方法也不难看出,弹出框内只能是UIViewController,而不能是UIView。
再者是弹出框的推送,类似于模态推送,弹出框的也不需要addSubview,而是使用的推送方法
- (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;
参数列表:触发推送事件控件的bounds,触发推送事件的控件,箭头方向,是否需要动画
2. 下面将开始讲解如何将UITableView封装到UIPopoverController中
① 定义弹出框和列表属性
@property (nonatomic, retain) UIPopoverController *popoverController;
@property (nonatomic, retain) UITableView *tableView;
② 初始化弹出框与列表
// 初始化弹出框中的列表视图
UIViewController *viewController = [[UIViewController alloc] init];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 180, 220) style:UITableViewStylePlain];
[viewController.view addSubview:_tableView];
// 设置事件代理以及数据代理
_tableView.delegate = self;
_tableView.dataSource = self;
// 初始化弹出框,弹出框中封装的必须是ViewController对象
self.popoverController = [[[UIPopoverController alloc] initWithContentViewController:self.tableVC] autorelease];
// 设置弹出框大小
self.popoverController.popoverContentSize = self.tableVC.tableView.bounds.size;
③ 设置列表代理,并实现代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
④ 弹出框推出方法(需要将推送方法的参数全部公开)
@property (nonatomic, assign) CGRect popoverFromRect; // 弹出框显示大小
@property (nonatomic, assign) UIPopoverArrowDirection arrowDiretion; // 弹出框箭头方向
@property (nonatomic, retain) NSArray *dataSource; // 弹出框中列表显示数据
@property (nonatomic, retain) UIView *inView; // 弹出框的父容器(由哪一个触发)
// 需要注意的是,防止inView的循环引用问题(只要不是inView = self,就不会出现该问题。本文代码并
⑤ 设置列表点击回调方法
// 定义代理
@protocol TJRPopoverViewDelegate
// 选中列表行后的回调方法
- (void)popoverViewDidSelectAtIndex:(NSInteger)index;
@end
// 在列表选中事件中,调用回调
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// 当选中列表某行以后,触发代理方法,将选中行的下标返回
[self.delegate popoverViewDidSelectAtIndex:indexPath.row];
}
这样,一个PopoverView就封装好了。源码以及使用方法下载地址:
https://github.com/saitjr/TJRPopoverView