How To Display Transparent Modal ViewControllers

Autor: | Última modificación: 9 de noviembre de 2022 | Tiempo de Lectura: 1 minutos
Temas en este post:

Transparent Modal View Controllers

I recently had to add a semi-transparent modal view controller on an app that I’m building for INSEAD. I was expecting to call  -presentModalViewController:animated: while modifying the alpha and opaque properties of the modal VC. It didn’t work.

The «problem» is that iOS is very finicky about not wasting memory, and since the modal view will completely cover the one beneath it, it doesn’t make much sense to keep it loaded. Therefore, iOS unloads the view that presents the modal one. You may check this behavior by implementing -viewWillDisappear: and -viewDidDisappear:.

DIY Transparent Modal View Controllers

The solution is to add the modal ViewControllers with addSubview: and animate the change in the view hierarchy with UIView’s animateWithDuration:delay:options:animations:completion:

Sample Code For Transparent Modal View Controllers

I added a property and 2 methods to a subclass of UIViewController (FRRViewController) that includes other functionalities. I will be publishing the whole stuff on gitHub soon, but until then you can see the relevant code on the transparent modal viewcontrollers gist.

BTW, the code assumes you are using ARC.