Show toast after dismiss the view iOS swift

 Problem:

I want to show the toast after dismiss the viewController in iOS swift


Solution:

extension UIViewController {

    func showToast(message : String, seconds: Double) {

        var errorMsg = message

        if message == "" {

            errorMsg = "Something went wrong! Please try again."

        }

        let label = ToastLabel()

        label.backgroundColor = UIColor(white: 0, alpha: 0.5)

        label.textColor = .white

        label.textAlignment = .center

        label.font = UIFont.systemFont(ofSize: 15)

        label.alpha = 0

        label.text = errorMsg

        label.clipsToBounds = true

        label.layer.cornerRadius = 20

        label.numberOfLines = 0

        label.textInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)

        label.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(label)

        

        let saveArea = view.safeAreaLayoutGuide

        label.centerXAnchor.constraint(equalTo: saveArea.centerXAnchor, constant: 0).isActive = true

        label.leadingAnchor.constraint(greaterThanOrEqualTo: saveArea.leadingAnchor, constant: 15).isActive = true

        label.trailingAnchor.constraint(lessThanOrEqualTo: saveArea.trailingAnchor, constant: -15).isActive = true

        label.bottomAnchor.constraint(equalTo: saveArea.bottomAnchor, constant: -30).isActive = true

        

        UIView.animate(withDuration: seconds, delay: 0, options: .curveEaseIn, animations: {

            label.alpha = 1

        }, completion: { _ in

            UIView.animate(withDuration: seconds * 2, delay: seconds, options: .curveEaseOut, animations: {

                label.alpha = 0

            }, completion: {_ in

                label.removeFromSuperview()

            })

        })

    }

}


You can call the show toast function inside the viewcontroller as like below


                    self.dismiss(animated:false){

                        self.showToast(message: "error message", seconds: 0.5)

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

store cgpoint in userdefaults iOS swift