iOS8.0開始推薦使用UIPopoverPresentationController,用于替代UIPopoverController。
UIPopoverPresentationController的使用方法類似于UIPopoverController,但是前者可以同時在iPhone和iPad上使用,這一點很不錯。
UIPopoverPresentationController并不是控制器類,而是繼承自NSObject,不能直接被彈出。其創建的方法發生于控制器內部的代碼:
self.modalPresentationStyle = UIModalPresentationPopover;
之后可以通過控制器的屬性popoverPresentationController獲取該對象。
以下是控制器部分的代碼,該控制器繼承自UITableViewController:
#import "HHContactsMenuController.h"
static NSString *const HHContactsMenuControllerID = @"HHContactsMenuControllerID";
@implementation HHContactsMenuController {
NSArray<NSString *> *titles;
}
- (instancetype)init {
self = [super init];
if (self) {
self.view.backgroundColor = ThemeColor();
self.modalPresentationStyle = UIModalPresentationPopover;
CGRect rect = CGRectMake(0, 0, 110, 96);
self.preferredContentSize = rect.size;
self.tableView.frame = rect;
self.tableView.backgroundColor = ThemeColor();
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:HHContactsMenuControllerID];
self.tableView.rowHeight = 32;
titles = @[@"創建群聊", @"管理家庭圈", @"管理好友"];
}
return self;
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HHContactsMenuControllerID forIndexPath:indexPath];
cell.textLabel.text = titles[indexPath.row];
cell.textLabel.textColor = UIWhiteColor();
cell.textLabel.font = [UIFont systemFontOfSize:13];
cell.backgroundColor = UIClearColor();
CGFloat xx = 15;
if (indexPath.row == 2) {
cell.separatorInset = UIEdgeInsetsMake(0, xx, 0, tableView.frame.size.width - xx);
} else {
cell.separatorInset = UIEdgeInsetsMake(0, xx, 0, 0);
}
return cell;
}
@end
其中UIPopoverPresentationController的代理adaptivePresentationStyleForPresentationController:一定要實現,并且返回值必須是UIModalPresentationNone!以下是調用部分的代碼:
- (void)rightBarButtonItemTapped:(id)sender {
HHContactsMenuController *cmc = HHContactsMenuController.new;
UIPopoverPresentationController *pop = cmc.popoverPresentationController;
pop.barButtonItem = self.navigationItem.rightBarButtonItem;
pop.permittedArrowDirections = UIPopoverArrowDirectionUp;
pop.backgroundColor = ThemeColor();
pop.delegate = self;
[self presentViewController:cmc animated:YES completion:^{
}];
}
#pragma mark- UIPopoverPresentationControllerDelegate
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
return UIModalPresentationNone;
}
iPad上的效果沒有試過....??