Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Present modal view controller in half size

Tags:

ios

swift

I tried to implement presenting modal view controller on the other UIViewController sized to half parent view controller as:

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)
    }
}

Now I need to dismiss my half sized view controller when user click the parent view controller.
How to achieve this?

like image 416
BB_Dev Avatar asked Jul 08 '15 09:07

BB_Dev


1 Answers

The following works: (Checked in Xcode 8.3 running Swift 3, iOS 10.2)

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)
}
}

Be sure to insert view at index 0

like image 103
Sabyasachee Baruah Avatar answered Oct 01 '22 23:10

Sabyasachee Baruah