iOS Blurred Background Modal View (Swift 3 + XCode Tutorial)

Mohau Mpoti
7 min readSep 22, 2017

--

One of the most popular UI features in iOS applications is the implementation of semi-transparent modal dialog (similar to the one displayed on the side). Reproducing this effect can be quite tricky (as I initially found out), and in this tutorial, I will show you the simplest way around creating a blurred background, semi-transparent modal view — in just 16 easy steps.

NB: The project can be downloaded at this repository>>

Step1.

Create a Single View Application and assign it an appropriate name.

Step 2.

Delete 2 of the files created by default, namely, ViewController.swift and LaunchScreen.storyboard. For reasons of tidiness, we’re cleaning up our file navigator to remove any unnecessary files before we proceed. If it’s your preference, you can skip this step.

Step 3.

Create 2 Cocoa Touch Classes (both of which are subclasses of UIViewController) and name them MainViewController and ModalViewController respectively.

Step 4.

Download>>, uncompress and drag 3image files to the Assets.xcassets folder. They will be referenced at a later stage, as we proceed with the project.

Step 5.

Switch the IDE Interface to the storyboard (Main.storyboard), drag an Image View UI element from the Object Library on to the default View Controller (stretching its edges out to fill the entire scene). Set its constraints as shown in the graphic below. With the Image View selected, go to the Attributes Inspector. On the Image attribute, select ‘Wallpaper’ from the drop-down.

Step 6.

Next, drag a Button UI element from the Object Library on to the default View Controller. With the Button selected, in the Attributes Inspector, change the default Title Text from’Button’ to ‘Open Modal View’. Change the default Text Color of the Button to White. Switch to the Size Inspector and change the Width of the Button to 200. Re-position the Button by placing it in the middle of the View Controller, and then set its constraints as shown below.

Step 7.

With the default View Controller selected, switch to the Identity Inspector and select the MainViewController class in the drop-down. That’s it! We’re done with UI configurations on the MainViewController. Get ready to switch to code…

Step 8.

With the MainViewController selected in the storyboard, click on the Assistant Editor icon (represented as 2 intersecting circles). That should result in a split-screen that shows the storyboard and the MainViewController.swift class side-by-side. Ctrl-drag the Button UI element on to an empty space in the MainViewController.swift class, creating an Action Connection (not an Outlet). Name it openModalView as shown below.

Step 9.

In the newly created method, openModalView, type in the enclosed code block as shown in the code segment below. This will be executed during navigation from the MainViewController to the ModalViewController (which we will create shortly). Be sure to add all the other methods as described below.

The utility of the method, overlayBlurredBackgroundView, is to overlay a dummy View that is blurred in appearance, at the moment that the UI navigates from the MainViewController to the ModalViewController. This is actually where the secret sauce of this project is!

The method, removeBlurredBackgroundView, will remove this dummy View when the UI navigates back to the MainViewController.

Finally, the prepare method is meant to perform some configurations before the UI navigates to the ModalViewController. Within this method, the segue object, which has an identifier of value == “ShowModalView”, will be created in the next steps. Ignore any visible errors for now. We’re almost there!

//  MainViewController.swift
// BlurredBackgroundSemiTransparentView
//
// Created by Mohau Mpoti on 19/9/17.
// Copyright © 2017 Swift Tutorials. All rights reserved.

import UIKit

class MainViewController: UIViewController {


@IBAction func openModalView(_ sender: Any) {
self.definesPresentationContext = true
self.providesPresentationContextTransitionStyle = true

self.overlayBlurredBackgroundView()
}


func overlayBlurredBackgroundView() {

let blurredBackgroundView = UIVisualEffectView()

blurredBackgroundView.frame = view.frame
blurredBackgroundView.effect = UIBlurEffect(style: .dark)

view.addSubview(blurredBackgroundView)

}

func removeBlurredBackgroundView() {

for subview in view.subviews {
if subview.isKind(of: UIVisualEffectView.self) {
subview.removeFromSuperview()
}
}
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "ShowModalView" {
if let viewController = segue.destination as? ModalViewController {
viewController.delegate = self
viewController.modalPresentationStyle = .overFullScreen
}
}
}
}

}

Step 10.

In the storyboard (Main.storyboard), drag a new ViewController from the Object Library to an empty space, adjacent to the the MainViewController. With the new View Controller selected, switch to the Identity Inspector and select the ModalViewController class from the drop-down.

Step 11.

Next, drag a Button from the Object Library on to the ModalViewController. With the Button selected, in the Attributes Inspector, select the image ‘Cancel’ from the Image attribute drop-down. In the Title Attribute, delete the default title (labeled ‘Button’) to an empty string. Last but not least, select the left-most setting of the Horizontal Alignment Attribute.

Step 12.

Re-position the Button to be located toward the top-left corner of the ModalViewController, and set its constraints as shown below.

Step 13.

Wire a Modal Segue (ctrl-drag) from the ‘Open Modal View’ Button (of the MainViewController) to the ModalViewController. With the new Segue selected in the storyboard, switch to the Attributes Inspector and in the identifier attribute, type in ‘ShowModalView’.

Step 14.

With the ModalViewController selected, click on the Assistant editor (which should show you a split-screen of the storyboard and ModalViewController.swift side-by-side). Ctrl drag from the Cancel Button to firstly create an Outlet named cancelButton, and thereafter an Action Connection named cancelButtonPressed.

Step 15.

In the newly created cancelButtonPressed method, type in the enclosed code block as shown below. This serves to close the ModalViewController.

Just before the ModalViewController class definition, define a new protocol named ModalViewControllerDelegate. We create this protocol here in order to delegate the responsibility of removing the dummy Blurred View (remember that?) we created in step 9, to the MainViewController.swift class. In the Swift language, protocols are a handy way of letting ViewControllers delegate certain tasks between each other, thereby keeping true to the Model-View-Controller (MVC) architecture of how the language is designed to best work.

Define a new instance variable named delegate as shown below. This will invoke the method declared within the newly created protocol when the ModalViewController is closed.

And finally, override the viewDidLayoutSubviews method, adding the enclosed code block as shown below. This performs some necessary formatting on different UI elements on the ModalViewController scene.

//
// ModalViewController.swift
// BlurredBackgroundSemiTransparentView
//
// Created by Mohau Mpoti on 19/9/17.
// Copyright © 2017 Swift Tutorials. All rights reserved.
//

import UIKit

protocol ModalViewControllerDelegate: class {
func removeBlurredBackgroundView()
}
class ModalViewController: UIViewController {

weak var delegate: ModalViewControllerDelegate?

@IBOutlet weak var cancelButton: UIButton!

@IBAction func cancelButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegate?.removeBlurredBackgroundView()
}

override func viewDidLayoutSubviews() {
view.backgroundColor = UIColor.clear

//ensure that the icon embeded in the cancel button fits in nicely
cancelButton.imageView?.contentMode = .scaleAspectFit

//add a white tint color for the Cancel button image
let cancelImage = UIImage(named: "Cancel")

let tintedCancelImage = cancelImage?.withRenderingMode(.alwaysTemplate)
cancelButton.setImage(tintedCancelImage, for: .normal)
cancelButton.tintColor = .white
}


}

Step 16.

One last thing. Phew!

Switch to the MainViewController.swift file, and add the just created protocol, ModalViewControllerDelegate, putting it in line with the class definition as shown below. This basically lets the ModalViewController class know that it will be responsible for defining and executing any methods declared within the protocol, in this case; removeBlurredBackgroundView( ).

class MainViewController: UIViewController, ModalViewControllerDelegate {...}

You can proceed to build and run the project.

Again, here’s where you can access the project at its repository>>

I invite you to also check out my pet project Spreebie here>>. Spreebie is a platform that navigates buyers to sellers nearby in real-time.

Cheers until next time,

-Mohau ;)

--

--

Mohau Mpoti

I’m co-founder at Spreebie, a platform that adds a personal touch to buying and selling. http://getspreebie.com/