Abed Naseri
Abed Naseri

Reputation: 512

Custom alertViewController in storyboard

I would like to show a popup (I just have UIAlertController in mind) like the the image below:

What I want to achieve

enter image description here

I found some kind of similar questions on the internet but they are code based, this way it is really hard to align the stuff in the position I want and handle the user interaction.

Is there a way that I kinda make a separate "Something" in the Storyboard and then here just pop that up? I thought of a whole ViewController but that covers the whole screen.

Any suggestions or solutions are highly appreciated. 🙏

Upvotes: 0

Views: 655

Answers (3)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need to present it modally , so make the VC give it identifier and load it anywhere

let vc = self.storyboard?.instantiateViewController(withIdentifier: "popupID") as! PopupViewController

vc.sendedStr = "someContent"

vc.myImage = UIImage(named:"flag.png")     

vc.providesPresentationContextTransitionStyle = true;

vc.definesPresentationContext = true;

vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext

self.present(vc, animated:true, completion: nil)

//

class PopupViewController : UIViewController {

    var sendedStr:String?

    var myImage:UIImage?      
}

More importantly is to set background of the view in IB like this enter image description here

Upvotes: 1

Abdul Rehman
Abdul Rehman

Reputation: 2456

First design viewController in storyBoard and keep in mind your ViewController main view background color should be either clear or change its Alpha to like 0.5

Add below extension

extension UIViewController {
    open func presentPOPUP(_ viewControllerToPresent: UIViewController, animated flag: Bool, modalTransitionStyle:UIModalTransitionStyle = .coverVertical, completion: (() -> Swift.Void)? = nil) {

        viewControllerToPresent.modalPresentationStyle = .overCurrentContext
        viewControllerToPresent.modalTransitionStyle = modalTransitionStyle

        self.present(viewControllerToPresent, animated: flag, completion: completion)

    }
}

After that you can use it like below

if let alerVC = self.myStoryBoard.instantiateViewController(withIdentifier: "AlertMessageVC") as? AlertMessageVC {
       self.presentPOPUP(alerVC, animated: true, modalTransitionStyle: .crossDissolve, completion: nil)
}

you can also change modalTransitionStyle to below options

 .coverVertical
 .flipHorizontal
 .crossDissolve
 .partialCurl

Hope this help. :)

Upvotes: 1

CZ54
CZ54

Reputation: 5588

ViewController Doesn't fill the entire screen all the time. This is just the default setting.

Set .modalPresentationStyle property of your child controller to .overCurrentContext and present it modally.

Now, if you view Controller has an transparent background, it will be presented like an alert.

Upvotes: 1

Related Questions