Swift:将popover的位置设置为屏幕中心

时间:2016-05-11 20:38:51

标签: ios swift

    var vc = segue.destinationViewController as UIViewController

    var controller = vc.popoverPresentationController

    vc.preferredContentSize=CGSize(width: UIScreen.mainScreen().bounds.width, height: 200)
    vc.view.bounds = CGRect(x: 10, y: 100, width: 10, height: 10)

我试图将我的popover的位置设置到设备的中心,我该怎么做,我基本上只是在你按下"之后试图通过自动成功机找出来。"

现在,我的代码中的最后一个语句没有做任何事情。 enter image description here

1 个答案:

答案 0 :(得分:0)

如果您希望从UIButton显示Popover,则需要设置sourceViewsourceRect属性。

  

界面中的UIView以及该视图坐标系中的CGRect,弹出框应与之关联。弹出箭头指向此矩形。通常,sourceView将是为了召唤弹出窗口而被轻击的视图,而sourceRect将是它的边界。

所以你需要这样的代码:

@IBAction func showPopover(sender: AnyObject) {

   var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("StoryboardIdentifier") as! UIViewController

   popoverContent.modalPresentationStyle = .Popover
   var popover = popoverContent.popoverPresentationController

   if let popover = popoverContent.popoverPresentationController {

      let viewForSource = sender as! UIView
      popover.sourceView = viewForSource

      // the position of the popover where it's showed
      popover.sourceRect = viewForSource.bounds

      // the size you want to display
      popoverContent.preferredContentSize = CGSizeMake(200,500)
      popover.delegate = self
   }            

   self.presentViewController(popoverContent, animated: true, completion: nil)
}

如果您使用popover segues,可以在prepareForSegue中手动配置,如上所示:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "MyPopover" {
        let dest = segue.destinationViewController
        if let pop = dest.popoverPresentationController {
            pop.delegate = self

            // set the rest of the properties as above
        }           
    }
}

我希望这对你有所帮助。