在iOS8之前Popover一直是iPad专属,iOS8新增的UIPopoverPresentationController替换原有的UIPopoverController,使得popover可以在iPad和iPhone上可以同时实现,UIPopoverPresentationController是UIPresentationController的子类,专门用来负责呈现popover的形式呈现内容。

最终要实现的效果

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("PopView")
viewController.modalPresentationStyle = .Popover
if let pctrl = viewController.popoverPresentationController {
pctrl.delegate = self
pctrl.barButtonItem = sender
self.presentViewController(viewController, animated: true, completion: nil)
}

你可以通过设置preferredContentSize调整弹出视图的大小

viewController.preferredContentSize = CGSize(width: 100, height: 130)

也可以通过设置sourceView,sourceRect这两个属性来决定弹出视图的位置,如果是想要弹出的视图在UIBarButtonItem的下方只需要设置barButtonItem即可。

在一般情况下调用UIViewController的presentViewController只是切换到下一个视图而已,我们需要实现UIPopoverPresentationControllerDelegate方法,在func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle方法中返回None

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.