UIPopoverPresentationController

(文章转载自:http://www.thomashanning.com/uipopoverpresentationcontroller/)

 

Since iOS 9, UIPopoverController is deprecated. Time to introduce the UIPopoverPresentationController, which is available since iOS 8.

 

Presenting a Controller as a Popover

Presenting a controller as a popover is very straightforward with UIPopoverPresentationController. You just have to set its  modalPresentationStyle property to UIModalPresentationStyle.Popover and present it with the  presentViewController method. UIKit then creates an UIPopoverPresentationController instance for you. This instance is accessible by a property of the controller you are presenting. However,  you have to configure it. If you don’t do this, there will be an exception at runtime. Let’s take a look at an example:

popover1

You have to set the  sourceView property of the UIPopoverPresentationController. Alternatively, you can also set the  barButtonItem property. UIKit needs this information to specify the location for the popover. Unfortunately, UIKit places the arrow in the upper left corner of the source view. In order to change this, you can assign a  sourceRect . UIKit sets the arrow just below that rect.

Additionally, we can specify the size of the popover by the  preferredContentSize property of the presented controller. Let’s expand our example:

 

popover2

It seems a little bit strange to configure the UIPopoverPresentationController after the call of presentViewController . However, the API documentation encourages you to do it this way.

UIPopoverPresentationControllerDelegate

If we want to have even more control over the popover, we can specify a delegate for the UIPopoverPresentationControllerDelegate:

Then, you can implement these methods:

The first one is called just before the popover is presented, the second after it is dismissed. With the third method you can control if the popover should be dismissed. For example, you can return false until the user has done some specific action in the popover.

iPhone

In the default configuration the popover is presented as a modal view controller on the iPhone. However, if you return  UIModalPresentationStyle.None in the adaptivePresentationStyleForPresentationController method of the UIPopoverPresentationControllerDelegate , you can present a popover also on the iPhone.

 

Conclusion

UIPopoverPresentationController makes handling popovers much easier. Use it, if you are targeting at least iOS 8.

References

Image: @ Rawpixel / shutterstock.com
UIPopoverPresentationController Class Reference
UIPopoverPresentationControllerDelegate

posted @ 2015-12-12 10:23  我叫南部21号  阅读(195)  评论(0)    收藏  举报