【问题标题】:Popup UIViewController弹出 UIViewController
【发布时间】:2016-05-13 09:07:43
【问题描述】:

我正在尝试制作一个弹出窗口,该弹出窗口将通过按下按钮呈现。尝试按照我在谷歌中找到的说明进行操作,但我的弹出视图以全屏形式呈现,并且其背景为黑色。 这是我的代码:

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    @IBAction func someButtonPressed(sender: UIButton) {
        let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let popupVC = storyboard.instantiateViewControllerWithIdentifier("hello") as! popupViewController
        popupVC.modalPresentationStyle = .Popover
        popupVC.preferredContentSize = CGSizeMake(300, 300)
        let pVC = popupVC.popoverPresentationController
        pVC?.permittedArrowDirections = .Any
        pVC?.delegate = self
        pVC?.sourceView = sender
        pVC?.sourceRect = CGRect(x: 100, y: 100, width: 1, height: 1)
        presentViewController(popupVC, animated: true, completion: nil)
    }
}

我做错了什么?

【问题讨论】:

标签: ios swift uiviewcontroller popup


【解决方案1】:

要使您的视图控制器显示为弹出窗口,您应该设置以下内容:

popupVC.modalPresentationStyle = .OverCurrentContext
popupVC.modalTransitionStyle = .CrossDissolve

您还应该设计视图控制器的位置、大小,使其看起来像一个弹出窗口。

这是我之前做的弹出窗口。

【讨论】:

  • 这是否可以通过编程方式实现。请解释
  • @n-der:你想以编程方式做什么?请解释一下。
  • 我想以编程方式将 UICollectionViewController 呈现为弹出窗口。谢谢。
  • @N.Der,是的,UIViewController 的任何部分(或子类)都可以。
【解决方案2】:

在父控制器:

let vc = ViewController()
vc.modalPresentationStyle = .overCurrentContext
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true, completion: nil)

在弹出的控制器中,使用它来启用在后台显示父控制器:

self.definesPresentationContext = true

别忘了为您的弹出式控制器设置一个半透明背景

-- 参考自:Presenting a popup view controller programmatically - Reddit--

【讨论】:

    【解决方案3】:

    另一个简单的解决方案,使用 EzPopup (https://github.com/huynguyencong/EzPopup)。非常简单,只需几行代码:

    // init YourViewController
    let contentVC = ...
    
    // Init popup view controller with content is your content view controller
    let popupVC = PopupViewController(contentController: contentVC, popupWidth: 100, popupHeight: 200)
    
    // show it by call present(_ , animated:) method from a current UIViewController
    present(popupVC, animated: true)
    

    【讨论】:

    • 2018-09-04 21:22:03.062970+0300 Project[58459:1907794] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“应用程序试图在本身。呈现控制器是 。' *** 首先抛出调用栈:
    • @MihailSalari 你应该从另一个视图控制器调用 present(...) 方法。
    • 这是一种不好的做法。
    • 为什么这是一个不好的做法?就像现在的其他视图控制器一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    相关资源
    最近更新 更多