Custom Alert (UIAlertView) with swift

前端 未结 5 1765
轻奢々
轻奢々 2020-11-28 09:16

How can i create a custom alert with Swift? I try translating a guide from Objective c but loads a full screen layout

for do it easy i can load a new layout with the

5条回答
  •  暖寄归人
    2020-11-28 09:58

    Here is the Swift 3 code. Thanks a lot @Suragch for the awesome approach to create a custom AlertView.

    ViewController.swift

    import UIKit
    class ViewController: UIViewController {
    
    @IBAction func showAlertButtonTapped(sender: UIButton) {
    
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let myAlert = storyboard.instantiateViewController(withIdentifier: "storyboardID")
            myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
            myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
            self.present(myAlert, animated: true, completion: nil)
    
    }
    

    AlertViewController.swift

    import UIKit
    class AlertViewController: UIViewController {
    
        @IBAction func dismissButtonTapped(sender: UIButton) {
            self.dismiss(animated: true, completion: nil)
        }
    }
    

    To make it a little more interesting or to make the default effect in iOS, you could add either a VisualEffectView or change the color of the main UIView to a dark color and set its alpha to 70%. I prefer the second approach since the blur effect is not as smooth as the one with the view with 70 alpha.

    Effect with VisualEffectView:

    Effect using a UIView with 70 Alpha:

提交回复
热议问题