swift - 如何在没有 Storyboard 的情况下在 Swift 中以编程方式调整弹出窗口的大小?

标签 swift popup

我正在尝试显示弹出 View ,但无法正确调整它的大小。我有以下代码显示我的弹出窗口,但 preferredContentSize 不起作用。查看总是全屏显示,这不是我想要的。如何正确调整弹出窗口的大小?

func presentPopup() {
        let popupVC = MyPopupViewController()
        popupVC.modalPresentationStyle = .overCurrentContext
        popupVC.modalTransitionStyle = .crossDissolve
        popupVC.popoverPresentationController?.permittedArrowDirections = .any
        // the following does not size the view, always come up full screen
        popupVC.preferredContentSize = CGSize(width: 200, height: 200) 
        present(popupVC, animated: true, completion: nil)
}

我想实现类似下面的东西。

enter image description here

请注意:我不使用 Storyboard,我正在寻找不使用或实例化 Storyboard的解决方案。

最佳答案

添加以下代码来实例化您的演示 Controller 并设置所需的配置。

let popupVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MyPopoverVC")
popupVC.modalPresentationStyle = .popover
popupVC.preferredContentSize = CGSize(width: 200, height: 200)

let presentationController = MyControllerPresentAsPopover.configurePresentation(forController: popupVC)
presentationController.sourceView = sender
presentationController.sourceRect = sender.bounds
presentationController.permittedArrowDirections = [.any]
present(popupVC, animated: true, completion: nil)

然后创建名为 MyControllerPresentAsPopover 的类,它实现了 UIPopoverPresentationControllerDelegate 的委托(delegate)方法。见下面的代码:

class MyControllerPresentAsPopover : NSObject, UIPopoverPresentationControllerDelegate {

    private static let sharedInstance = MyControllerPresentAsPopover()

    private override init() {
        super.init()
    }

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }

    static func configurePresentation(forController controller : UIViewController) -> UIPopoverPresentationController {
        controller.modalPresentationStyle = .popover
        let presentationController = controller.presentationController as! UIPopoverPresentationController
        presentationController.delegate = MyControllerPresentAsPopover.sharedInstance
        return presentationController
    }
}

关于swift - 如何在没有 Storyboard 的情况下在 Swift 中以编程方式调整弹出窗口的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885872/

相关文章:

iOS 11 UITableView 中的额外顶部空间

javascript - FB.login() 调用弹出窗口被 Google Chrome 阻止

javascript - 下拉动画联系人框

iOS:如何减少 Storyboard 和代码重复?

swift - NSData/Data 存储是否连续?

ios - 如何将 UIImage 正确地锚定到位于自定义单元格中的 UIView 中?

html - 如何将固定的div固定到其他div的底部?

c# - 不透明度未应用于 WPF 弹出控件

swift - 如何在 NSMenuItems 的自定义 View 中弹出 NSMenu?

swift - 无法使用 Swift 3 修改自定义 collectionView 中的标签单元格