Is there any way to Toast message in swift ?
I have tried in objective c but could not find solution in swift.
[self.view makeToast:@\"Account create
Mr. Beans answer works well. However, his answer uses a small width & isn't multi-line friendly. Use this instead.
func showToastFaded(message : String) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 125, y: self.view.frame.size.height-100, width: 250, height: 35))
toastLabel.numberOfLines = 0
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
toastLabel.sizeToFit()
toastLabel.frame = CGRect( x: toastLabel.frame.minX, y: toastLabel.frame.minY,width: toastLabel.frame.width + 20, height: toastLabel.frame.height + 8)
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
What exactly you need is https://github.com/Rannie/Toast-Swift/blob/master/SwiftToastDemo/Toast/HRToast%2BUIView.swift .
Download the HRToast + UIView.swift class and drag and drop to project. Make sure you check 'copy items if needed' on dialogue box.
//Usage:
self.view.makeToast(message: "Simple Toast")
self.view.makeToast(message: "Simple Toast", duration: 2.0, position:HRToastPositionTop)
self.view.makeToast(message: "Simple Toast", duration: 2.0, position: HRToastPositionCenter, image: UIImage(named: "ic_120x120")!)
self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionDefault, title: "Simple Toast")
self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionCenter, title: "Simple Toast", image: UIImage(named: "ic_120x120")!)
self.view.makeToastActivity()
self.view.makeToastActivity(position: HRToastPositionCenter)
self.view.makeToastActivity(position: HRToastPositionDefault, message: "Loading")
self.view.makeToastActivityWithMessage(message: "Loading")
I have been using this extension when ever i need toast-message like android.. Just copy the extension to you project and then in your UIViewController class, call the function like
self.toastMessage("Downloading...")
// Extention is below
extension UIViewController {
func toastMessage(_ message: String){
guard let window = UIApplication.shared.keyWindow else {return}
let messageLbl = UILabel()
messageLbl.text = message
messageLbl.textAlignment = .center
messageLbl.font = UIFont.systemFont(ofSize: 12)
messageLbl.textColor = .white
messageLbl.backgroundColor = UIColor(white: 0, alpha: 0.5)
let textSize:CGSize = messageLbl.intrinsicContentSize
let labelWidth = min(textSize.width, window.frame.width - 40)
messageLbl.frame = CGRect(x: 20, y: window.frame.height - 90, width: labelWidth + 30, height: textSize.height + 20)
messageLbl.center.x = window.center.x
messageLbl.layer.cornerRadius = messageLbl.frame.height/2
messageLbl.layer.masksToBounds = true
window.addSubview(messageLbl)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
UIView.animate(withDuration: 1, animations: {
messageLbl.alpha = 0
}) { (_) in
messageLbl.removeFromSuperview()
}
}
}}
I know there are accepted answers but they all seem to have a big flaw - if you show several toasts in a short period of time they will show on top of each other. Here is my implementation which takes this problem into consideration:
class Toast: UILabel {
private let BOTTOM_MARGIN: CGFloat = 16
private let SIDE_MARGIN: CGFloat = 16
private let HEIGHT: CGFloat = 35
private let SHOW_TIME_SECONDS = TimeInterval(3)
private let BACKGROUND_COLOR = UIColor.darkGray.withAlphaComponent(0.7).cgColor
private let TEXT_COLOR = UIColor.white
private let ANIMATION_DURATION_SEC = 0.33
private static var queue: [ToastHolder] = []
private static var showing: Toast?
init(_ text: String) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
self.text = text
self.textColor = TEXT_COLOR
textAlignment = .center
self.layer.backgroundColor = BACKGROUND_COLOR
self.layer.cornerRadius = 5
}
public func show(_ parent: UIViewController) {
frame = CGRect(x: SIDE_MARGIN, y: UIScreen.main.bounds.height - BOTTOM_MARGIN - HEIGHT, width: UIScreen.main.bounds.width - 2 * SIDE_MARGIN, height: HEIGHT)
if Toast.showing == nil {
Log.d("showing \(String(describing: text))")
Toast.showing = self
alpha = 0
parent.view.addSubview(self)
UIView.animate(withDuration: ANIMATION_DURATION_SEC, animations: {
self.alpha = 1
}, completion: { (completed) in
Timer.scheduledTimer(timeInterval: self.SHOW_TIME_SECONDS, target: self, selector: #selector(self.onTimeout), userInfo: nil, repeats: false)
})
} else {
Toast.queue.append(ToastHolder(self, parent))
}
}
@objc func onTimeout() {
UIView.animate(withDuration: ANIMATION_DURATION_SEC, animations: {
self.alpha = 0
}, completion: { (completed) in
Toast.showing = nil
self.removeFromSuperview()
if !Toast.queue.isEmpty {
let holder = Toast.queue.removeFirst()
holder.toast.show(holder.parent)
}
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("this initializer is not supported")
}
private class ToastHolder {
let toast: Toast
let parent: UIViewController
init(_ t: Toast, _ p: UIViewController) {
toast = t
parent = p
}
}
}
Usage:
Toast("my message").show(self)
Hope it helps someone.
I have modified the @samo's answer with:
Proper variables name's
Leading and Trailing constraints changed to center constraint.
Now message will adjust its width according to message and it will be centred.
extension UIViewController {
func showToast(message: String) {
let toastContainer = UIView(frame: CGRect())
toastContainer.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastContainer.alpha = 0.0
toastContainer.layer.cornerRadius = 20;
toastContainer.clipsToBounds = true
let toastLabel = UILabel(frame: CGRect())
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font.withSize(12.0)
toastLabel.text = message
toastLabel.clipsToBounds = true
toastLabel.numberOfLines = 0
toastContainer.addSubview(toastLabel)
self.view.addSubview(toastContainer)
toastLabel.translatesAutoresizingMaskIntoConstraints = false
toastContainer.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: toastLabel, attribute: .centerX, relatedBy: .equal, toItem: toastContainer, attribute: .centerXWithinMargins, multiplier: 1, constant: 0)
let lableBottom = NSLayoutConstraint(item: toastLabel, attribute: .bottom, relatedBy: .equal, toItem: toastContainer, attribute: .bottom, multiplier: 1, constant: -15)
let lableTop = NSLayoutConstraint(item: toastLabel, attribute: .top, relatedBy: .equal, toItem: toastContainer, attribute: .top, multiplier: 1, constant: 15)
toastContainer.addConstraints([centerX, lableBottom, lableTop])
let containerCenterX = NSLayoutConstraint(item: toastContainer, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let containerTrailing = NSLayoutConstraint(item: toastContainer, attribute: .width, relatedBy: .equal, toItem: toastLabel, attribute: .width, multiplier: 1.1, constant: 0)
let containerBottom = NSLayoutConstraint(item: toastContainer, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -75)
self.view.addConstraints([containerCenterX,containerTrailing, containerBottom])
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
toastContainer.alpha = 1.0
}, completion: { _ in
UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: {
toastContainer.alpha = 0.0
}, completion: {_ in
toastContainer.removeFromSuperview()
})
})
}
}
extension UIViewController {
func showToast(message : String, font: UIFont) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
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: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
} }
Use like this:
self.showToast(message: "Your Toast Message", font: .systemFont(ofSize: 12.0))