Popover不以按钮为中心

use*_*915 19 uipopovercontroller ios swift

我试图将一个弹出按钮放在一个按钮上.我似乎无法弄清楚我可能会出错的地方.它不是按钮位于按钮中间,而是偏离屏幕宽度的一半.

 @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)
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 57

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

popoverPresentationViewController?.sourceView = sender as! UIButton
popoverPresentationViewController?.sourceRect = sender.frame
Run Code Online (Sandbox Code Playgroud)

没有!你的意思是界限:

popoverPresentationViewController?.sourceView = sender as! UIButton
popoverPresentationViewController?.sourceRect = (sender as! UIButton).bounds
Run Code Online (Sandbox Code Playgroud)

原因是它sourceRect是在坐标空间中给出的sourceView- 也就是说,如果你想让它成为视图的rect,它就是那个视图的界限.


Sco*_*ner 48

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
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 不适合我.我正在使用此代码.让popoverViewController = segue.destinationViewController popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover popoverViewController.popoverPresentationController!.delegate = self if let let popoverPresentationController = segue.destinationViewController.popoverPresentationController,sourceView = sender as?UIView {popoverPresentationController.sourceRect = sourceView.bounds} (2认同)