前言
學習的時候遺漏了這個知識點,最近在做一個類微信、支付寶的 "+"號彈出浮窗的功能,發現了這個好用的東西~ 做個記錄方便日后查閱
NS_CLASS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED //iOS8之后可用 @interface UIPopoverPresentationController : UIPresentationController
基本使用
效果圖
點擊pop按鈕后觸發的Action代碼如下
/* Present the view controller using the popover style. */
// 每個viewController,都有一個modalPresentationStyle屬性
TestViewController * test = [[TestViewController alloc]init];
test.preferredContentSize = CGSizeMake(300, 200);//設置浮窗的寬高
test.modalPresentationStyle = UIModalPresentationPopover;
/* Get the popover presentation controller and configure it. */
//獲取TestViewController的UIPopoverPresentationController
UIPopoverPresentationController * popover = [test popoverPresentationController];
popover.delegate = self;
popover.permittedArrowDirections = UIPopoverArrowDirectionUp;//設置箭頭位置
popover.sourceView = self.popViewButton;//設置目標視圖
popover.sourceRect = self.popViewButton.bounds;//彈出視圖顯示位置
popover.backgroundColor = [UIColor redColor];//設置彈窗背景顏色(效果圖里紅色區域)
[self presentViewController:test animated:YES completion:nil];
** UIPopoverPresentationControllerDelegate代理方法 **
/*
For iOS8.0, the only supported adaptive presentation styles
are UIModalPresentationFullScreen and UIModalPresentationOverFullScreen. */
// 設置 浮窗彈窗的推出樣式,效果圖中設置style為UIModalPresentationNone
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:
(UIPresentationController *)controller;
// Called on the delegate when the popover controller will dismiss the popover. Return NO to prevent the
// dismissal of the view.
// 點擊浮窗背景popover controller是否消失
- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController;
// Called on the delegate when the user has taken action to dismiss the popover. This is not called when the popover is dimissed programatically.
// 浮窗消失時調用
- (void)popoverPresentationControllerDidDismissPopover:(UIPopoverPresentationController *)popoverPresentationController;
防止點擊UIPopoverController區域外消失
默認情況下
只要UIPopoverController顯示在屏幕上,UIPopoverController背后的所有控件默認是不能跟用戶進行正常交互的
點擊UIPopoverController區域外的控件,UIPopoverController默認會消失
要想點擊UIPopoverController區域外的控件時不讓UIPopoverController消失,解決辦法是設置passthroughViews屬性
@property (nonatomic, copy) NSArray *passthroughViews;
這個屬性是設置當UIPopoverController顯示出來時,哪些控件可以繼續跟用戶進行正常交互。這樣的話,點擊區域外的控件就不會讓UIPopoverController消失了
寫在最后
官網對UIPopoverPresentationController介紹
Human Interface Guidelines——Popovers