iOS SDK: Create a Pop Up window

iOS - Pop Up window
iOS – Popup window

In an iOS project I am currently working on, I was requested to create a pop-up window. Trying to figure out how to do it, I came up with a solution that is pretty easy to implement and very straight forward. All you need is a view controller with a transparent background and a subview (your popup window). After creating the popUpViewController, you can just call it from any other view controller.

Lets see the implementation in depth. First we create a new objective-c class with .xib file. In the header file (.h), add the following code (we need the QuarzCore framework in the project to style the window with rounded corners and shadows):

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"

@interface PopUpViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *popUpView;

- (void)showInView:(UIView *)aView animated:(BOOL)animated;

@end

After that edit the .xib file so it looks like the one in the image below.

popup-xib
Interface Builder view of the popup window.

Now connect the popUpView outlet to the view in the .xib file (the view highlighted int he above image). Next, open the .m file of your class and add the following lines in your viewDidLoad method, so the background view of the window looks transparent:

- (void)viewDidLoad
{
    self.view.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:.6];
    self.popUpView.layer.cornerRadius = 5;
    self.popUpView.layer.shadowOpacity = 0.8;
    self.popUpView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

Note that we set the backgroundColor alpha and not the view alpha because the popup window is a subview of the background view and we do not want it to look transparent too. In the viewDidLoad method we also set the shadow of the window and the cornerRadius (in order to get rounded corners).

Finally lets implement the code that does the trick with pop up fade in and fade out:

- (void)showAnimate
{
    self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.view.alpha = 0;
    [UIView animateWithDuration:.25 animations:^{
        self.view.alpha = 1;
        self.view.transform = CGAffineTransformMakeScale(1, 1);
    }]; 
}

- (void)removeAnimate
{
    [UIView animateWithDuration:.25 animations:^{
        self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.view.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self.view removeFromSuperview];
        }
    }];
}

The showAnimate method scales the view to 1.3 (130%) of its current size, sets the alpha to 0 and then invokes an animation block with a duration of 0.25 sec that scales the view down to its original size and sets the alpha to 1. The removeAnimate method does exactly the opposite and implements also a completion handler for the animation block, so we know when to remove it from its superview.

Finally we need the IBAction for the close button, so the removeAnimate method is called and the implementation for the showInView method that we declared in our .h file in order to show our popup window on top of other views. The code here is self-explanatory:

- (IBAction)closePopup:(id)sender {
    [self removeAnimate];
}

- (void)showInView:(UIView *)aView animated:(BOOL)animated
{
    [aView addSubview:self.view];
    if (animated) {
        [self showAnimate];
    }
}

Connect the IBAction to the “Close” button you’ve added in your .xib and you are done. The output will look like this:

Popup demonstration
Popup demonstration

 

The code is available on Github alongside with a simple view that demonstrates how this popup can be invoked from other view controllers. A new post regarding the Swift implementation of the PopUp is also available here.

 

43 thoughts on “iOS SDK: Create a Pop Up window

  1. Hi I used your code to create a popup window but I’m encountering a EXC_BAD_ACCESS error whenever I try to close the popup… Can you suggest a solution? Thanks!

    1. @tina you get this probably because the popup view gets released. Are you declaring it a s a property (like in my example) or you do declare it within your button code. Declare it a strong property like in my example in Github. You can refer to this twitter discussion for a further issue.

      1. Hi Nikos, thanks for your reply. I got it working by following your suggestion of setting the popup as a strong property. Great job btw! Yours is the best popup window I’ve seen so far because of the animation and how I can customize the view 🙂

  2. Hi , your blog help me a lot , thanks.
    But in this post , i used your code to create a popup view , but the popup view didn’t have rounded corners.Why?

    1. @dee this is because a small change Apple did in iOS 7.1 sdk. In this code
      self.view.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:.6];
      self.popUpView.layer.cornerRadius = 5;
      self.popUpView.layer.shadowOpacity = 0.8;
      self.popUpView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
      add one more line:

      self.popUpView.clipsToBounds = YES;

  3. I have already added this line of code to my project . Finally i solved this problem .
    But thanks anyway .
    : ]

      1. There’s no problem with the code. Hey , Nikos M , can you give me a hint how to test this popup view controller? Thank you very much.

  4. Hi Nikos,

    Thank you for this wonderful popup, I used some of your code for my app and I’ve put your name on the credit list. 🙂

    Will send you the link when the app is on Appstore.

  5. Great code! One question: the popupView does not resize when I use it in a 3.5 inch device.
    What do I still need to set? I turned off Autolayout and use Autosizing settings in Interface Builder…

    1. @Robert the popupView uses Autolayout constraints to fit various displays sizes so you should leave Autolayout on for the popupView (and use the constraints I use in the sample app if you don’t use the .xib included in the tutorial).

    1. @Anuj: You can download the project from github to see a complete working example with code for the “Show” button. If you do not want the Swift version I’ve recently added, download release version 1.0 of the code which is Objective-C only.

  6. I ran your project it was working good, but when I implemented this on my project, it shows up well but app crashed on closing the popup view, with EXC_BAD_ACCESS error. Would you please, help me solve the mystery?

    Thanks

        1. Hi Nikos,
          Wonderful code 🙂 I’ve imported POPUpViewController.h and .m and also POPUpViewController_ipad.xib and POPUpViewController.xib into my project. I made the popupview as a strong property in PopUpViewController.h
          I still get the error of EXC_BAD_ACCESS error when I close the popup. How can I fix this issue?

          1. Hi Hedieh,

            You have to declare the PopUpViewController as a strong property in your view controller where you are calling it. Not declare the popup view as strong in the PopUpViewController.h file I provide. If you have further issues feel free to open an issue on Github and I will check it.

  7. hi nikos,
    i have developed my application xcode 6 + ios 7 the pop up working well in devise. But when i run the app in simulator, popup not working as well as when i run the application in iphone 6 device (ios 8) its not working. Kindly help me on this

    1. @Padma, I’ve tested it on both iPhone 6 (iOS 8.1) and iphone 5/5s (iOS 8.1) and it works fine (both the Swift and Obj-C version). If you keep having issues, open an issue on github and post the error you are getting, so I can assist you there.

  8. Hi Nikos! I wonder if you can please help. I have followed your tutorial and github code but i still keep seeing this error:

    libc++abi.dylib: terminating with uncaught exception of type NSException

    I have managed to simulate your pop up fine, it is when I try to incorporate it into my own code/app I have a problem. I wonder if I need to set the constraints as I have not done so?

  9. Am using swift same issue happening when i close the popup window my app get crash.. i dnt knw how to declare the PopUpViewController as a strong property in my view controller … kindly explain

    1. In Swift properties are declared as strong by default unless you declare them as weak. If you need further help please post the crash log in the github repository issues (there is already an open issue for this).

  10. Dear sir:
    that’s an amazing work, but I got a question, once I clicked the “close”, then got a black screen.
    May you help me to deal with that?

    Thanks.

    1. @owen: Thats a known issue but I have not figured out how to solve it. Visit the github repository (link within the post) and post the crash log there (in the issues section) so I can assist you further. Github issue

  11. i ran your project. But i customised your popup view. i designed tableview . Inside the table view cell i have individual button when the button is clicked its push to one view controller . Everything is working fine. When i click the button the popup view will shown with tableview details . What is my problem is when i click the tableview cell button its not push to represented view controller. This is my problem . can you give me some ideas please, Thanks in advance

    1. @roby: The problem is that you are trying to push a controller from the popup and the popupviewcontroller does not have a navigation controller. There two ways to solve this: add a navigation controller to popupviewcontroller so you can push controllers or when clicking a tableview cell: dismiss the popup first and then push the controller you want from the controller that showed the popup (you can add a protocol to pass information from the popup to the view controller).

  12. Amazing Project!

    Has any tried this on iOS 9.2? Cant seem to dismiss the view by clicking the “Close” button.
    I am running on an actual device from objective-C code above

    Thanks in advance,

    1. Disregard!! problem fixed!

      Was missing the below the header file of the view controller that calls the generic popover controller:

      @property (strong, nonatomic) PopOverViewController * popOverVC;

  13. Hello,
    Great tutorial and example code.
    I am trying to use this pop up to show up when clicking a button placed in a cell, the pop up window show up just fine.
    when I am trying to click the close button the pop up window does not disappear, actually the event is not being caught by the click on the button at all.

    Can you help?

  14. Hi,

    When I am implement this code I am getting crash like this:-

    Terminating app due to uncaught exception ‘CALayerInvalid’, reason: ‘layer is a part of cycle in its layer tree’

    I don’t know why it is?
    I want show the PopView

    Help me any one….

  15. HI,
    Firstly,Thank You for the tutorial.
    And I have a problem on close Button.
    While I’m clicking the close button, the popup will not closed.
    can you please help me for this problem

    1. Sorry, latest version is swift only. You can get the Objective-C branch from github which is an objective-c old version of the code but this is no longer maintained.

  16. hi, your pop up works fine but i can’t close it. the view which i am calling it from overrides the view by that i mean i can interact with a background view on the pop up and cant interact or dismiss the pop up.

    1. whoooo! managed to solve it by myself. ahhh in was suppose to add addChildviewController and did move to parent controller methods.

  17. Hi, I applied your post to my project. I used it when my collection view cell is called; however, I could not trigger the event for any thing as buttons. I think it related to delegate, do you have any idea about it?
    my cell click:
    – (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attributes = [wordsCollection layoutAttributesForItemAtIndexPath:indexPath];
    CGRect cellFrameInSuperview = [wordsCollection convertRect:attributes.frame toView:[wordsCollection superview]];

    PopupViewController *popViewController = [[PopupViewController alloc]
    initWithNibName:@”PopupViewController” bundle:nil];
    [popViewController setTitle:@”This is a popup view”];
    [self.view addSubview:popViewController.view];
    [popViewController showInView:self.view animated:YES frame:cellFrameInSuperview];

    }
    the action not working in my popup.m
    – (IBAction)addFavorite:(id)sender {
    NSLog(@”Action has been called”);
    [self removeAnimate];
    }

Leave a Reply to Maruthi Cancel 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.