提出半尺寸的模态视图控制器

我试图在另一个大小为半父视图控制器的UIViewController上实现modal view controller ,如下所示:

 class ViewController: UIViewController, UIViewControllerTransitioningDelegate { override func viewDidLoad() { super.viewDidLoad() } @IBAction func tap(sender: AnyObject) { var storyboard = UIStoryboard(name: "Main", bundle: nil) var pvc = storyboard.instantiateViewControllerWithIdentifier("CustomTableViewController") as UITableViewController pvc.modalPresentationStyle = UIModalPresentationStyle.Custom pvc.transitioningDelegate = self pvc.view.backgroundColor = UIColor.redColor() self.presentViewController(pvc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { return HalfSizePresentationController(presentedViewController: presented, presentingViewController: presenting) } } class HalfSizePresentationController : UIPresentationController { override func frameOfPresentedViewInContainerView() -> CGRect { return CGRect(x: 0, y: 0, width: containerView.bounds.width, height: containerView.bounds.height/2) } } 

现在,当用户单击父视图控制器时,我需要关闭我的半角视图控制器。
怎么做到这一点?

您只需要在HalfSizePresentationController中添加一个UIView(可能是一个调光视图)。 然后向该视图添加一个点击手势识别器,以处理将被调用以关闭呈现视图的点击事件:

 func dimmingViewTapped(tapRecognizer: UITapGestureRecognizer) { presentingViewController.dismissViewControllerAnimated(true, completion: nil) } 

也许这会有所帮助:http: //zappdesigntemplates.com/custom-presentations-using-uipresentationcontroller-swift/

我知道为时已晚。 但下面是实现这一目标的最简单答案。

 self.view.backgroundColor = UIColor.clearColor() self.datePicker.backgroundColor = UIColor.whiteColor() self.modalTransitionStyle = .CoverVertical self.modalPresentationStyle = .OverCurrentContext 

self是视图控制器,它正在呈现。

以下工作:(在运行Swift 3,iOS 10.2的Xcode 8.3中检查)

 class HalfSizePresentationController: UIPresentationController { let backgroundView = UIView() override var frameOfPresentedViewInContainerView: CGRect { // your implementation } override func presentationTransitionDidEnd(_ completed: Bool) { if completed { backgroundView.frame = (containerView?.frame)! let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AddMenuPresentationController.dismissPVC(_:))) backgroundView.addGestureRecognizer(tapGestureRecognizer) containerView?.insertSubview(backgroundView, at: 0) } } override func dismissalTransitionDidEnd(_ completed: Bool) { if completed { backgroundView.removeFromSuperview() } } func dismissPVC(_ gestureRecognizer: UIGestureRecognizer) { self.presentedViewController.dismiss(animated: true, completion: nil) } } 

请务必在索引0处插入视图