salient
salient

Reputation: 2486

Set custom size of presenting modal in Swift fails — occupies full screen

How can I get a presenting modal to be of custom size? Tried lots of different solutions, many which seem obsolete

This is how I instantiate the modal view from the parent view controller:

self.definesPresentationContext = true
let vc = (storyboard?.instantiateViewController(withIdentifier: "modalViewController"))!
vc.modalPresentationStyle = .overCurrentContext
vc.preferredContentSize = CGSize(width: 100, height: 100)
present(vc, animated: true, completion: nil)

But, the modal view covers the full screen instead of just occupying 100 * 100.

Upvotes: 0

Views: 3641

Answers (1)

PGDev
PGDev

Reputation: 24341

You need to implement UIViewControllerTransitioningDelegate methods and UIViewControllerAnimatedTransitioning methods for customizing the presented UIViewController size.

To know how to implement custom animator,

Refer to: https://github.com/pgpt10/Custom-Animator

Edit:

class ViewController: UIViewController
{
    //MARK: Private Properties
    fileprivate let animator = Animator()

    //MARK: View Lifecycle Methods
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()
        self.transitioningDelegate = self
        self.modalPresentationStyle = .custom
    }

    //MARK: Button Action Methods
    @IBAction func dismissController(_ sender: UIButton)
    {
        self.dismiss(animated: true, completion: nil)
    }
}

// MARK: - UIViewControllerTransitioningDelegate Methods
extension ViewController : UIViewControllerTransitioningDelegate
{
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        self.animator.transitionType = .zoom
        self.animator.size = CGSize(width: 100, height: 100)
        return self.animator
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        return self.animator
    }
}

Upvotes: 1

Related Questions