Created
January 17, 2019 03:24
-
-
Save shishirthedev/43decdc385ff9c9a9dd2cf15b27933e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIView { | |
func displayToast(_ message : String) { | |
guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else { | |
return | |
} | |
if let toast = window.subviews.first(where: { $0 is UILabel && $0.tag == -1001 }) { | |
toast.removeFromSuperview() | |
} | |
let toastView = UILabel() | |
toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7) | |
toastView.textColor = UIColor.white | |
toastView.textAlignment = .center | |
toastView.font = UIFont(name: "Font-name", size: 17) | |
toastView.layer.cornerRadius = 25 | |
toastView.text = message | |
toastView.numberOfLines = 0 | |
toastView.alpha = 0 | |
toastView.translatesAutoresizingMaskIntoConstraints = false | |
toastView.tag = -1001 | |
window.addSubview(toastView) | |
let horizontalCenterContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0) | |
let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: (self.frame.size.width-25) ) | |
let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[toastView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["toastView": toastView]) | |
NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint]) | |
NSLayoutConstraint.activate(verticalContraint) | |
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: { | |
toastView.alpha = 1 | |
}, completion: nil) | |
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: { | |
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: { | |
toastView.alpha = 0 | |
}, completion: { finished in | |
toastView.removeFromSuperview() | |
}) | |
}) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment