iOS SDK: Pop up window in Swift

popup13

One of the most popular posts in my blog is the tutorial for creating a Pop-up window with iOS SDK using Objective-C. Since then many readers reached me out asking for a Swift version of the Pop-up. In general the process is exactly the same in Swift (except the language used to write the code of course…), so I am not going to dive into the process of creating the .xib files again. For this you can always refer to the original post.

The Pop-up controller is a subclass of UIViewController with a couple of methods for the fade in and fade out animations.

 override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
        self.popUpView.layer.cornerRadius = 5
        self.popUpView.layer.shadowOpacity = 0.8
        self.popUpView.layer.shadowOffset = CGSizeMake(0.0, 0.0)
    }
    
    func showInView(aView: UIView!, withImage image : UIImage!, withMessage message: String!, animated: Bool)
    {
        aView.addSubview(self.view)
        logoImg!.image = image
        messageLabel!.text = message
        if animated
        {
            self.showAnimate()
        }
    }
    
    func showAnimate()
    {
        self.view.transform = CGAffineTransformMakeScale(1.3, 1.3)
        self.view.alpha = 0.0;
        UIView.animateWithDuration(0.25, animations: {
            self.view.alpha = 1.0
            self.view.transform = CGAffineTransformMakeScale(1.0, 1.0)
        });
    }
    
    func removeAnimate()
    {
        UIView.animateWithDuration(0.25, animations: {
            self.view.transform = CGAffineTransformMakeScale(1.3, 1.3)
            self.view.alpha = 0.0;
            }, completion:{(finished : Bool)  in
                if (finished)
                {
                    self.view.removeFromSuperview()
                }
        });
    }
    
    @IBAction func closePopup(sender: AnyObject) {
        self.removeAnimate()
    }

In the viewDidLoad method, I styled the PopUp with rounded corners. You can customize that for square corners or other shadow styles. Note that in Swift we have to implement also the required init(coder aDecoder: NSCoder) and as we’ve created the UI in interface builder using .XIBs the override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) method has to be added too. Add these two methods and we are almost done:

required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

Now that the PopUp is implemented, we have to call it from the view where we want to display it.

self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil)
self.popViewController.title = "This is a popup view"
self.popViewController.showInView(self.view, withImage: UIImage(named: "typpzDemo"), withMessage: "You just triggered a great popup window", animated: true)

A fully working example alongside with the Objective-C and Swift code for the PopUp is available on Github. Feel free to use it in your projects and if you find any issue or glitch, do not hesitate to open an issue on Github.

A video version of the tutorial is provided by Webucator.

 

23 thoughts on “iOS SDK: Pop up window in Swift

  1. Hi thank you for this tutorial! I was able to make the pop up window appear, but gets an error whenever I try to close it. Bad access. IN your tutorial, are you referring to the popup window at the whole viewcontroller itself/ or just the small view inside it? And which of the two should I make reference to and where? Sorry I got confused.

    1. @Raymond yes you have to refer the popup window as a viewController in your view. You can refer to the github examples to see exactly how to use it. If you are still having issues, please open an issue on github so other users can refer to it too.

  2. Great tutorial thanks a lot! Just one question, where did you set the size for the popup?

    I couldn’t find it in your code, is this done with the constraints or something…

    In the viewdidLoad of where Im calling it I added
    self.popUpView.frame = CGRectMake(0, 0, 75, 75) I would of thought it would be as simple as that… But Im obviously looking in the wrong place, just need to edit the example somewhere?!

    1. @Mattporter() The size for the popUp is determined using autolayout constraints in the .xib files. You should modify it there as you like. Using .frame property to explicitly set the frame has no affect when using autolayout.

  3. Amazing tutorial , the example project worked fine. I was trying to add a scrollView in the xib files, but scrolling wasn’t working. I updated the reference to the UIView and replaced it with scrollView, everything shows up fine but scrolling isn’t working. Tried enabling scrolling via code, still not working. Any thought how would you enable a popup screen that allow users to scroll ?

    1. @tatwan: Set the ScrollView contentSize property (it is a CGSize property) to be a little bigger in height than the screen height. For example:

      scrollView.contentSize = CGSizeMake(UIScreen.mainScreen().bounds.size.widht, UIScreen.mainScreen().bounds.size.height+30)

      1. That was it, thank you very much. I had originally modified the view size in xib file to be same height as scrollview during development which was causing the issue. Thanks again.

  4. Hi,

    I tried to call it when a button is tapped but it shows “unexpectedly found nil while unwrapping an Optional value” fatal error.

    If I put comment to following three lines in viewDidLoad method then I can see the background view (with alpha component 0.6).

    self.popUpView.layer.cornerRadius = 5
    self.popUpView.layer.shadowOpacity = 0.8
    self.popUpView.layer.shadowOffset = CGSizeMake(0.0, 0.0)

    So I guess, I am having some problem on displaying popUpView.

    Can you spread some light on it?

    Thanks in advance

    1. @Narendra you have to initialize the popUpView first. For example:

      @IBAction func showPopUp(sender: AnyObject) {
      if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
      {
      self.popViewController = PopUpViewControllerSwift(nibName: “PopUpViewController_iPad”, bundle: nil)
      self.popViewController.title = “This is a popup view”
      self.popViewController.showInView(self.view, withImage: UIImage(named: “typpzDemo”), withMessage: “You just triggered a great popup window”, animated: true)
      } else
      {
      if UIScreen.mainScreen().bounds.size.width > 320 {
      if UIScreen.mainScreen().scale == 3 {
      self.popViewController = PopUpViewControllerSwift(nibName: “PopUpViewController_iPhone6Plus”, bundle: nil)
      self.popViewController.title = “This is a popup view”
      self.popViewController.showInView(self.view, withImage: UIImage(named: “typpzDemo”), withMessage: “You just triggered a great popup window”, animated: true)
      } else {
      self.popViewController = PopUpViewControllerSwift(nibName: “PopUpViewController_iPhone6”, bundle: nil)
      self.popViewController.title = “This is a popup view”
      self.popViewController.showInView(self.view, withImage: UIImage(named: “typpzDemo”), withMessage: “You just triggered a great popup window”, animated: true)
      }
      } else {
      self.popViewController = PopUpViewControllerSwift(nibName: “PopUpViewController”, bundle: nil)
      self.popViewController.title = “This is a popup view”
      self.popViewController.showInView(self.view, withImage: UIImage(named: “typpzDemo”), withMessage: “You just triggered a great popup window”, animated: true)
      }
      }
      }

      After initializing apply the effects on the layer and present the popup. Mo info can be found here and in the Github repo readme.

  5. I have followed the tutorial and I am getting the popup to show up on my initial VC but my button is not responding to touch. I have it linked to the IBAction touch up inside. I have changed the look of the popup so my buttons are buried in subview of the popup would that cause an issue?

  6. Hi Nikos! Thank you for this great tutorial!
    Is it possible to add a timer to close automatically the popup after a certain time?

  7. Thank your for the great tutorial. Everything is working well for me except getting my iphone6plus xib to show. My 6 one shows fine. The error I got was the view outlet was not set for the 6Plus xib. My question is how do I set that on my xib VC when I already have one for my 6?

    1. @malcolm: You can connect multiple xibs to the same class. So just drag the outlet from the view to the view property and it will be fine. You can post the issue on Github if you need further help.

  8. Hi
    Thanks for time saving tutorial.
    I hv done implement, and Xib popoup, when I try close, there is no action triggered. I did verified the “TouchInside” action. There is no call from screen to @IBACTION function during touch. do u have any idea, why this problem?

  9. Close Button doesn’t respond. So i created new button to try and i created IBAction but again it doesn’t respond. What is the problem ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.