Skip to content

Instantly share code, notes, and snippets.

@JangSungChul
Last active February 3, 2021 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JangSungChul/29422302552143d2d8b37b1b9dabc992 to your computer and use it in GitHub Desktop.
Save JangSungChul/29422302552143d2d8b37b1b9dabc992 to your computer and use it in GitHub Desktop.
# 1.1 Toast Message like Android
extension UIViewController {
func showToast(message : String, time: TimeInterval) {
let font:UIFont = .systemFont(ofSize: 12.0)
let fontAttributes = [NSAttributedString.Key.font: font]
let size = (message as NSString).size(withAttributes: fontAttributes)
var width: CGFloat = size.width
var height: CGFloat = 35
if (width > self.view.frame.size.width - 20) {
height = height * ceil(width / (self.view.frame.size.width - 20))
width = self.view.frame.size.width - 20
}
let toastLabel = UILabel(frame: CGRect(x: (self.view.frame.size.width / 2) - (width / 2), y: self.view.frame.size.height / 2, width: width, height: height))
toastLabel.lineBreakMode = .byCharWrapping
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.font = font
toastLabel.textAlignment = .center;
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 0.5, delay: time, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment