popup不在button上

我正在尝试将一个popup窗口放在一个button上。 我似乎无法弄清楚我可能会出错的地方。 而不是button中间的箭头,它是偏离屏幕宽度的一半。

@IBAction func buttonClicked(sender: AnyObject){ var popoverViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ServiceOptions") as! ServiceOptionsPopover popoverViewController.delegate = self popoverViewController.modalPresentationStyle = .Popover popoverViewController.preferredContentSize = CGSizeMake(300, 300) let popoverPresentationViewController = popoverViewController.popoverPresentationController popoverPresentationViewController?.permittedArrowDirections = .Up popoverPresentationViewController?.delegate = self popoverPresentationViewController?.sourceView = sender as! UIButton popoverPresentationViewController?.sourceRect = sender.frame presentViewController(popoverViewController, animated: true, completion: nil) } 

问题是混乱的框架和边界的基本问题:

 popoverPresentationViewController?.sourceView = sender as! UIButton popoverPresentationViewController?.sourceRect = sender.frame 

没有! 你的意思是:

 popoverPresentationViewController?.sourceView = sender as! UIButton popoverPresentationViewController?.sourceRect = (sender as! UIButton).bounds 

原因在于sourceRect是在sourceRect的坐标空间中sourceView – 也就是说,如果你想让它成为视图的矩形,它就是这个视图的边界。

iOS 9中存在一个问题。在故事板中设置锚点:

在这里输入图像说明

…导致箭头不在锚的中心:

在这里输入图像说明

要解决,请将此添加到prepareForSegue:sender: ::

 // Fixes popover anchor centering issue in iOS 9 if let popoverPresentationController = segue.destinationViewController.popoverPresentationController, sourceView = sender as? UIView { popoverPresentationController.sourceRect = sourceView.bounds } 

在这里输入图像说明

这是正确的方法:

 @IBAction func buttonClicked(sender: UIButton){ var popoverViewController = UIViewController() popoverViewController.view.frame = CGRectMake(0,0, 300, 300) popoverViewController.view.backgroundColor = UIColor.redColor() popoverViewController.modalPresentationStyle = .Popover popoverViewController.preferredContentSize = CGSizeMake(300, 300) let popoverPresentationViewController = popoverViewController.popoverPresentationController popoverPresentationViewController?.permittedArrowDirections = .Up popoverPresentationViewController?.sourceView = sender popoverPresentationViewController?.sourceRect = CGRectMake(0, 0, sender.bounds.width,sender.bounds.height) // see this line of code presentViewController(popoverViewController, animated: true, completion: nil) }