0

I've successfully created an extension on UIViewController that allows me to call a function that triggers a UIView to animate down. However instead of just a plain UIView, I want to improve on the extension so that it is it takes two parameters (background color, and label text) that are a subview on the UIView 'popupAlert?

extension UIViewController {

func showAlert() {
    let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
    popupAlert.backgroundColor = UIColor.brandSuccess()
    let window = (UIApplication.shared.delegate as! AppDelegate).window!

    window.addSubview(popupAlert)

    UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
        popupAlert.transform = .init(translationX: 0, y: 60)
    }) { (_) in
        UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: -60)

        }, completion: { (_) in
            popupAlert.removeFromSuperview()
        })
    }
}
}
Marwen Doukh
  • 1,946
  • 17
  • 26
unicorn_surprise
  • 951
  • 2
  • 21
  • 40
  • Possible duplicate of [How to have stored properties in Swift, the same way I had on Objective-C?](https://stackoverflow.com/questions/25426780/how-to-have-stored-properties-in-swift-the-same-way-i-had-on-objective-c) – 10623169 May 30 '19 at 11:56
  • There is no text in given method – RajeshKumar R May 30 '19 at 11:58
  • Yeah I'm not sure where to put the text, it would be to be centered in the popupAlert UIView. Does that make sense? – unicorn_surprise May 30 '19 at 12:06
  • it is a kinda extremely bad practice to alter (i.e. add / remove) the `UIWindow` instance's subviews directly. – holex May 30 '19 at 12:35

1 Answers1

4
extension UIViewController {

    func showAlert(bgColor: UIColor, lblText: String) {
        let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
        let popupLbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60))
        popupAlert.backgroundColor = bgColor
        popupLbl.text = lblText
        popupLbl.textColor = .green
        popupLbl.textAlignment = .center
        let window = (UIApplication.shared.delegate as! AppDelegate).window!

        popupAlert.addSubview(popupLbl)
        window.addSubview(popupAlert)

        UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
            popupAlert.transform = .init(translationX: 0, y: 60)
        }) { (_) in
            UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
                popupAlert.transform = .init(translationX: 0, y: -60)

            }, completion: { (_) in
                popupAlert.removeFromSuperview()
            })
        }
    }
}

call

    showAlert(bgColor: .red, lblText: "testtttt")
Ben Rockey
  • 920
  • 6
  • 23