我正在尝试显示弹出 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)
}
我想实现类似下面的东西。
请注意:我不使用 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/