Skip to content

Instantly share code, notes, and snippets.

@mickspecial
Created March 5, 2019 04:57
Show Gist options
  • Save mickspecial/ec9788424d848f072441f100a1577b4c to your computer and use it in GitHub Desktop.
Save mickspecial/ec9788424d848f072441f100a1577b4c to your computer and use it in GitHub Desktop.
Toast alert for Swift
final class Toast {
private var parentView: UIView!
private var hideAfter: TimeInterval!
private var toastLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.black
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = UIFont.systemFont(ofSize: 18)
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
return label
}()
var toastView: UIView = {
let v = UIView(frame: .zero)
v.translatesAutoresizingMaskIntoConstraints = false
v.alpha = 0
return v
}()
@discardableResult
convenience init(display label: String, on vc: UIViewController, hideAfter: TimeInterval = 1.5) {
self.init()
parentView = vc.view
toastLabel.text = label
self.hideAfter = hideAfter
setupView()
animateToast()
}
private func animateToast() {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
self.toastView.alpha = 1.0
}, completion: { _ in
UIView.animate(withDuration: 0.5, delay: self.hideAfter, options: .curveEaseOut, animations: {
self.toastView.alpha = 0.0
}, completion: {_ in
self.toastView.removeFromSuperview()
})
})
}
private func addVisualEffect() {
toastView.backgroundColor = .clear
let style = UIBlurEffect.Style.regular
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: style))
visualEffectView.frame = toastView.bounds
visualEffectView.layer.cornerRadius = 25
visualEffectView.clipsToBounds = true
visualEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
toastView.addSubview(visualEffectView)
}
private func setupView() {
addVisualEffect()
toastView.addSubview(toastLabel)
parentView.addSubview(toastView)
NSLayoutConstraint.activate([
toastView.widthAnchor.constraint(equalToConstant: 280),
toastView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
toastView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
toastLabel.leadingAnchor.constraint(equalTo: toastView.leadingAnchor, constant: 15),
toastLabel.trailingAnchor.constraint(equalTo: toastView.trailingAnchor, constant: -15),
toastLabel.topAnchor.constraint(equalTo: toastView.topAnchor, constant: 15),
toastLabel.bottomAnchor.constraint(equalTo: toastView.bottomAnchor, constant: -15)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment