Skip to content

Instantly share code, notes, and snippets.

@bhrott
Last active July 9, 2017 18:18
Show Gist options
  • Save bhrott/e6801ea235a959a659116730f1d60e45 to your computer and use it in GitHub Desktop.
Save bhrott/e6801ea235a959a659116730f1d60e45 to your computer and use it in GitHub Desktop.
Simple top toast on swift 3

Usage

Toast.show(withMessage: "My message")

Result

toast

import Foundation
import UIKit
class Toast {
static func show(withMessage message: String, withHeight height: CGFloat = 60.0, withDuration duration: TimeInterval = 3.0, withBackgroundColor backgroundColor: UIColor = UIColor.black, withTextColor textColor: UIColor = UIColor.white) {
let view = UIApplication.shared.keyWindow!
let toastLabel = UILabel(frame: CGRect(x: 0.0, y: -height, width: UIScreen.main.bounds.width, height: height))
toastLabel.backgroundColor = backgroundColor
toastLabel.textColor = textColor
toastLabel.textAlignment = .center;
toastLabel.text = "\n\(message)"
toastLabel.font = toastLabel.font.withSize(12)
toastLabel.numberOfLines = 2
toastLabel.alpha = 1.0
toastLabel.clipsToBounds = true
view.addSubview(toastLabel)
UIView.animate(withDuration: 0.2, animations: {
toastLabel.frame.origin.y = 0
}) { _ in
UIView.animate(withDuration: 0.2, delay: duration, animations: {
toastLabel.frame.origin.y = -height
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment