Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active November 3, 2022 10:04
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save barbietunnie/e5547f35180436ac102cac52a15f8ca3 to your computer and use it in GitHub Desktop.
Save barbietunnie/e5547f35180436ac102cac52a15f8ca3 to your computer and use it in GitHub Desktop.
Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .OverCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Seque with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

Background = Clear Color
Drawing = Uncheck the Opaque checkbox
Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Source

@RakeshFM
Copy link

RakeshFM commented Feb 9, 2018

This will not work with tabbar app. over current context open the model from below the tabbar

@ngdinhkhoa120691
Copy link

How to dismiss ModalViewController from MainViewController? T_T

@satjava
Copy link

satjava commented Aug 17, 2018

great job

@satjava
Copy link

satjava commented Aug 17, 2018

make a button on modal

and make its action

@IBAction func closeBtn(_ sender: Any) {
dismiss(animated: true, completion: nil)
}

@naveedahmad99
Copy link

Button is not showing on Modal Screen

@zafar007
Copy link

thanks

@granitmehmeti
Copy link

doesent work for me, with tab bar I think doesnt work.!

@ZvOlCuOk2009
Copy link

does not work, the lower controller is removed after half a second

@Narek1994
Copy link

For tab bars u can use .overFullScreen

@bovillaios
Copy link

For tab bars u can use .overFullScreen

Working

@mrousavy
Copy link

Is there a way to do this without using Modals? I've created a custom animation between two view controllers and have some animation stuff going on (Shared Element Transitions) that don't work in a Modal context...

@wshrads
Copy link

wshrads commented Oct 6, 2020

Works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment