UIPopoverPresentationController使用


UIPopoverPresentationController是什么?

iOS8.0之后引入的一個方便開發者創建帶箭頭的彈出控制器,類似qq消息頁面點擊右上角加號彈出的視圖。繼承UIPresentationController類,可用於iPhone和iPad ,比之前的UIPopoverController使用方便。下面給出實現的效果圖:

UIPopoverPresentationController怎么使用?

UIPopoverPresentationControllerl類實例不需要直接創建,因為在UIViewController中有一個popoverPresentationController屬性,可以從它獲取。

這里給出基本的使用方法:

第一步:

創建一個UIViewController類的實例,最好采用他的子類,對它進行一些設置,這里我們設置了preferredContentSize屬性和modalPresentationStyle,modalPresentationStyle一定要設置為UIModalPresentationPopover,而preferredContentSize可以不設置,不設置的話,系統會自動給一個幾乎充滿整個屏幕的視圖。

ItemPopoverViewController *controller = [[ItemPopoverViewController alloc] init]; controller.preferredContentSize = CGSizeMake(100, 100); controller.modalPresentationStyle = UIModalPresentationPopover;  

 

第二步:

對UIPopoverPresentationController進行設置,

首先看一下UIPopoverPresentationController中的一些屬性,從下圖可以看到sourceViewbarButtonItem,sourceView是用於UIView類及其子類的,barButtonItem用於UIBarButtonItem,這兩個屬性是告訴UIPopoverPresentationController實例出現在哪個視圖上,區別在於sourceView還需要指定sourceRect,否則pop出來的視圖位置將不正確,一般我們給sourceRect賦當前視圖的bounds屬性就可以了。

@property (nullable, nonatomic, strong) UIView *sourceView;
@property (nonatomic, assign) CGRect sourceRect;

// By default, a popover is not allowed to overlap its source view rect.
// When this is set to YES, popovers with more content than available space are allowed to overlap the source view rect in order to accommodate the content.
@property (nonatomic, assign) BOOL canOverlapSourceViewRect NS_AVAILABLE_IOS(9_0);

@property (nullable, nonatomic, strong) UIBarButtonItem *barButtonItem;

現在看看demo里的代碼

// 出現在UIBarButtonItem上面的
UIPopoverPresentationController *popController = [controller popoverPresentationController]; popController.delegate = self; popController.barButtonItem = self.barItem;
// 出現在view上面的
UIPopoverPresentationController *popController = [controller popoverPresentationController]; popController.sourceView = self.button; popController.sourceRect = self.button.bounds; popController.delegate = self;

從上面代碼可以看出這兩種方式區別不大,注意到我們在這里指定了delegate屬性,這是很重要的,下面將介紹它的作用。

第三步:

這是最后一步,控制器要顯示,就需要用present的方法

[self presentViewController:controller animated:YES completion:nil];

 同樣的,要消失的話,調用下面這個方法

[self dismissViewControllerAnimated:YES completion:nil];

 

到這里,基本上我們已完成了所有內容,但是如果你看效果的話,會發現,並不是pop出一個視圖,而是占據整個屏幕的視圖,相信你還記得上面提到的代理,我們需要實現一個方法:

- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

加上這個之后,就能看到pop出來的效果了。

UIPopoverPresentationController顯示內容

如果要顯示內容,只需在相應視圖控制器中添加內容即可,但是,因為一般我們都會設置preferredContentSize這個屬性,設置了之后,顯示的視圖往往比較小,在viewDidLoad中控制器的根視圖大小還不是我們設置的preferredContentSize這個值,不能用來做參考,創建的子視圖的大小可以在viewWillLayoutSubviews或者viewDidLayoutSubviews中進行更新。

以上就是UIPopoverPresentationController基本用法.

 

demo下載地址:下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM