How to add android like toast in iOS?












3














In android we can add toast directly.
Is their any method to add similar toast in iOS?



I created the transparent view to use as toast but for multiple text sizes i have to create more than one view.










share|improve this question




















  • 3




    Here are Many : cocoacontrols.com/search?q=toast
    – Nitin Gohel
    Jan 2 '17 at 6:27










  • what else you need with android here, kindly update.
    – vaibhav
    Jan 2 '17 at 7:06
















3














In android we can add toast directly.
Is their any method to add similar toast in iOS?



I created the transparent view to use as toast but for multiple text sizes i have to create more than one view.










share|improve this question




















  • 3




    Here are Many : cocoacontrols.com/search?q=toast
    – Nitin Gohel
    Jan 2 '17 at 6:27










  • what else you need with android here, kindly update.
    – vaibhav
    Jan 2 '17 at 7:06














3












3








3


0





In android we can add toast directly.
Is their any method to add similar toast in iOS?



I created the transparent view to use as toast but for multiple text sizes i have to create more than one view.










share|improve this question















In android we can add toast directly.
Is their any method to add similar toast in iOS?



I created the transparent view to use as toast but for multiple text sizes i have to create more than one view.







ios objective-c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 '17 at 7:45









vaibhav

3,30611238




3,30611238










asked Jan 2 '17 at 6:26









Deovrat Deshmukh

314




314








  • 3




    Here are Many : cocoacontrols.com/search?q=toast
    – Nitin Gohel
    Jan 2 '17 at 6:27










  • what else you need with android here, kindly update.
    – vaibhav
    Jan 2 '17 at 7:06














  • 3




    Here are Many : cocoacontrols.com/search?q=toast
    – Nitin Gohel
    Jan 2 '17 at 6:27










  • what else you need with android here, kindly update.
    – vaibhav
    Jan 2 '17 at 7:06








3




3




Here are Many : cocoacontrols.com/search?q=toast
– Nitin Gohel
Jan 2 '17 at 6:27




Here are Many : cocoacontrols.com/search?q=toast
– Nitin Gohel
Jan 2 '17 at 6:27












what else you need with android here, kindly update.
– vaibhav
Jan 2 '17 at 7:06




what else you need with android here, kindly update.
– vaibhav
Jan 2 '17 at 7:06












8 Answers
8






active

oldest

votes


















4














There is no Android type Toast control available in iOS.



If you want to use something like it, you need to customise UIView with UILabel, or use some already created Toast type component, like below:



Android Type Toast custom






share|improve this answer































    1














    You can use MBProgressHUD to show a toast like android. After adding MBProgressHUD you can display a toast by this way



            let progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
    progressHUD.mode = MBProgressHUDMode.text
    progressHUD.detailsLabel.text = "Your message here"
    progressHUD.margin = 10.0
    progressHUD.offset.y = 150.0
    progressHUD.isUserInteractionEnabled = false
    progressHUD.removeFromSuperViewOnHide = true
    progressHUD.hide(animated: true, afterDelay: 3.0)





    share|improve this answer





























      1














      You can use this function to display toast message in iOS. Just create the extension on the view and call this method with the message.



      Swift 4



      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()
      })
      })
      }
      }


      usage:



      just call view.displayToast("Hello World") from UIViewController






      share|improve this answer























      • That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
        – decades
        Nov 19 '18 at 17:58












      • thanks. please upvote if you like the answer.
        – Suhit Patil
        Nov 19 '18 at 18:05










      • @decades updated for swift 4
        – Suhit Patil
        Nov 19 '18 at 18:24










      • Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
        – decades
        Nov 20 '18 at 19:20



















      0














      There is a 3rd party library that supports customizable toast notification with single line of code. Here is a simple example of it:



      import Toast_Swift

      ...

      // basic usage
      self.view.makeToast("This is a piece of toast")

      // toast with a specific duration and position
      self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)


      Toast Swift library



      Or else,



      If you want to implement by your own. Use below code.



      let toastLabel = UILabel(frame: CGRectMake(self.view.frame.size.width/2 - 150, self.view.frame.size.height-100, 300, 35))
      toastLabel.backgroundColor = UIColor.blackColor()
      toastLabel.textColor = UIColor.whiteColor()
      toastLabel.textAlignment = NSTextAlignment.Center;
      self.view.addSubview(toastLabel)
      toastLabel.text = "hello man..."
      toastLabel.alpha = 1.0
      toastLabel.layer.cornerRadius = 10;
      toastLabel.clipsToBounds = true
      UIView.animateWithDuration(4.0, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: {

      toastLabel.alpha = 0.0

      })





      share|improve this answer





















      • This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
        – decades
        Nov 19 '18 at 18:02



















      0














      This is best library I used for showing Toast in iOS apps same as android.



      It also has pod support and pod name is pod 'Toast'



      And implementation is so simple like



      #import <UIView+Toast.h>


      in your ViewController and then following line wherever you want to show it



      [self.view makeToast:@"YOUR TOAST MESSAGE" duration:TOAST_TIMEOUT position:TOAST_CENTER];


      Value for above keys are



      #define TOAST_TOP @"CSToastPositionTop"
      #define TOAST_CENTER @"CSToastPositionCenter"
      #define TOAST_BOTTOM @"CSToastPositionBottom"
      #define TOAST_TIMEOUT 2.0





      share|improve this answer





















      • No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
        – decades
        Nov 20 '18 at 19:26



















      0














      there is no ThostView in iOS. we Can custom are use 3rd party libraries.
      follow this link -




      • https://github.com/scalessec/Toast-Swift






      share|improve this answer





























        0














        An attempt to make Suhit Pal's answer above Swift 4 like with a way to remove an existing Toast once a new appears



        extension UIView {

        private static var toastView: UILabel? = nil

        func displayToast(message : String, duration: Double? = 3.0) -> Void {
        if UIView.toastView != nil {
        UIView.toastView!.removeFromSuperview()
        }
        UIView.toastView = UILabel()
        UIView.toastView!.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        UIView.toastView!.textColor = UIColor.white
        UIView.toastView!.textAlignment = .center
        UIView.toastView!.font = UIFont(name: "Font-name", size: 17)
        UIView.toastView!.layer.masksToBounds = true
        UIView.toastView!.layer.cornerRadius = 25
        UIView.toastView!.text = message
        UIView.toastView!.numberOfLines = 0
        UIView.toastView!.alpha = 0
        UIView.toastView!.translatesAutoresizingMaskIntoConstraints = false

        let window = UIApplication.shared.delegate?.window!
        window?.addSubview(UIView.toastView!)

        let horizontalCenterContraint : NSLayoutConstraint = NSLayoutConstraint(item: UIView.toastView!, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
        let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: UIView.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)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": UIView.toastView!])

        NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
        NSLayoutConstraint.activate(verticalContraint)

        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
        UIView.toastView!.alpha = 1
        }, completion: nil)

        DispatchQueue.main.asyncAfter(deadline: .now() + duration!) {
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
        UIView.toastView!.alpha = 0
        }, completion: { (_) in
        UIView.toastView!.removeFromSuperview()
        })
        }
        }
        }





        share|improve this answer





























          0














          Here is my latest version of this. It allows to cancel an existing toast by just pushing a new. It also allows to provide an optional "reverseColors" parameter, which writes white on black instead default black on white. The toast adapts to the text size with a little margin left and right.



          extension UIView {

          private static var toastView: UILabel? = nil
          private static var toastViewCancelTask : DispatchWorkItem?

          func displayToast(message : String, duration: Double, reverseColors: Bool? = false) -> Void {
          if UIView.toastView != nil {
          UIView.toastView!.removeFromSuperview()
          UIView.toastViewCancelTask?.cancel()
          }


          UIView.toastView = UILabel()
          UIView.toastViewCancelTask = DispatchWorkItem {
          UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
          UIView.toastView!.alpha = 0
          }, completion: { (_) in
          UIView.toastView!.removeFromSuperview()
          })
          }

          let toastView = UIView.toastView!
          print(message)

          if reverseColors != nil && reverseColors! {
          toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
          toastView.textColor = UIColor.white
          }
          else {
          toastView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
          toastView.textColor = UIColor.black
          }
          toastView.textAlignment = .center
          toastView.font = UIFont.systemFont(ofSize: 17)
          toastView.layer.masksToBounds = true
          toastView.layer.cornerRadius = 12
          toastView.text = message
          toastView.numberOfLines = 0
          toastView.alpha = 0
          toastView.sizeToFit()
          toastView.translatesAutoresizingMaskIntoConstraints = false

          let width = toastView.frame.size.width + 100 > self.frame.size.width ? self.frame.size.width - 100 : toastView.frame.size.width + 100

          let window = UIApplication.shared.delegate?.window!
          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: width )
          let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-30-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

          NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
          NSLayoutConstraint.activate(verticalContraint)

          UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
          toastView.alpha = 0.8
          }, completion: nil)

          DispatchQueue.main.asyncAfter(deadline: .now() + duration , execute: UIView.toastViewCancelTask!)
          }

          }





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41422251%2fhow-to-add-android-like-toast-in-ios%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            4














            There is no Android type Toast control available in iOS.



            If you want to use something like it, you need to customise UIView with UILabel, or use some already created Toast type component, like below:



            Android Type Toast custom






            share|improve this answer




























              4














              There is no Android type Toast control available in iOS.



              If you want to use something like it, you need to customise UIView with UILabel, or use some already created Toast type component, like below:



              Android Type Toast custom






              share|improve this answer


























                4












                4








                4






                There is no Android type Toast control available in iOS.



                If you want to use something like it, you need to customise UIView with UILabel, or use some already created Toast type component, like below:



                Android Type Toast custom






                share|improve this answer














                There is no Android type Toast control available in iOS.



                If you want to use something like it, you need to customise UIView with UILabel, or use some already created Toast type component, like below:



                Android Type Toast custom







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 2 '17 at 8:04









                dirtydanee

                4,36121429




                4,36121429










                answered Jan 2 '17 at 6:33









                Dheeraj D

                2,36121025




                2,36121025

























                    1














                    You can use MBProgressHUD to show a toast like android. After adding MBProgressHUD you can display a toast by this way



                            let progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
                    progressHUD.mode = MBProgressHUDMode.text
                    progressHUD.detailsLabel.text = "Your message here"
                    progressHUD.margin = 10.0
                    progressHUD.offset.y = 150.0
                    progressHUD.isUserInteractionEnabled = false
                    progressHUD.removeFromSuperViewOnHide = true
                    progressHUD.hide(animated: true, afterDelay: 3.0)





                    share|improve this answer


























                      1














                      You can use MBProgressHUD to show a toast like android. After adding MBProgressHUD you can display a toast by this way



                              let progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
                      progressHUD.mode = MBProgressHUDMode.text
                      progressHUD.detailsLabel.text = "Your message here"
                      progressHUD.margin = 10.0
                      progressHUD.offset.y = 150.0
                      progressHUD.isUserInteractionEnabled = false
                      progressHUD.removeFromSuperViewOnHide = true
                      progressHUD.hide(animated: true, afterDelay: 3.0)





                      share|improve this answer
























                        1












                        1








                        1






                        You can use MBProgressHUD to show a toast like android. After adding MBProgressHUD you can display a toast by this way



                                let progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
                        progressHUD.mode = MBProgressHUDMode.text
                        progressHUD.detailsLabel.text = "Your message here"
                        progressHUD.margin = 10.0
                        progressHUD.offset.y = 150.0
                        progressHUD.isUserInteractionEnabled = false
                        progressHUD.removeFromSuperViewOnHide = true
                        progressHUD.hide(animated: true, afterDelay: 3.0)





                        share|improve this answer












                        You can use MBProgressHUD to show a toast like android. After adding MBProgressHUD you can display a toast by this way



                                let progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
                        progressHUD.mode = MBProgressHUDMode.text
                        progressHUD.detailsLabel.text = "Your message here"
                        progressHUD.margin = 10.0
                        progressHUD.offset.y = 150.0
                        progressHUD.isUserInteractionEnabled = false
                        progressHUD.removeFromSuperViewOnHide = true
                        progressHUD.hide(animated: true, afterDelay: 3.0)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 2 '17 at 6:40









                        Usman Javed

                        1,392719




                        1,392719























                            1














                            You can use this function to display toast message in iOS. Just create the extension on the view and call this method with the message.



                            Swift 4



                            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()
                            })
                            })
                            }
                            }


                            usage:



                            just call view.displayToast("Hello World") from UIViewController






                            share|improve this answer























                            • That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                              – decades
                              Nov 19 '18 at 17:58












                            • thanks. please upvote if you like the answer.
                              – Suhit Patil
                              Nov 19 '18 at 18:05










                            • @decades updated for swift 4
                              – Suhit Patil
                              Nov 19 '18 at 18:24










                            • Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                              – decades
                              Nov 20 '18 at 19:20
















                            1














                            You can use this function to display toast message in iOS. Just create the extension on the view and call this method with the message.



                            Swift 4



                            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()
                            })
                            })
                            }
                            }


                            usage:



                            just call view.displayToast("Hello World") from UIViewController






                            share|improve this answer























                            • That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                              – decades
                              Nov 19 '18 at 17:58












                            • thanks. please upvote if you like the answer.
                              – Suhit Patil
                              Nov 19 '18 at 18:05










                            • @decades updated for swift 4
                              – Suhit Patil
                              Nov 19 '18 at 18:24










                            • Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                              – decades
                              Nov 20 '18 at 19:20














                            1












                            1








                            1






                            You can use this function to display toast message in iOS. Just create the extension on the view and call this method with the message.



                            Swift 4



                            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()
                            })
                            })
                            }
                            }


                            usage:



                            just call view.displayToast("Hello World") from UIViewController






                            share|improve this answer














                            You can use this function to display toast message in iOS. Just create the extension on the view and call this method with the message.



                            Swift 4



                            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()
                            })
                            })
                            }
                            }


                            usage:



                            just call view.displayToast("Hello World") from UIViewController







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 19 '18 at 18:31

























                            answered Jan 2 '17 at 6:41









                            Suhit Patil

                            6,78322242




                            6,78322242












                            • That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                              – decades
                              Nov 19 '18 at 17:58












                            • thanks. please upvote if you like the answer.
                              – Suhit Patil
                              Nov 19 '18 at 18:05










                            • @decades updated for swift 4
                              – Suhit Patil
                              Nov 19 '18 at 18:24










                            • Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                              – decades
                              Nov 20 '18 at 19:20


















                            • That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                              – decades
                              Nov 19 '18 at 17:58












                            • thanks. please upvote if you like the answer.
                              – Suhit Patil
                              Nov 19 '18 at 18:05










                            • @decades updated for swift 4
                              – Suhit Patil
                              Nov 19 '18 at 18:24










                            • Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                              – decades
                              Nov 20 '18 at 19:20
















                            That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                            – decades
                            Nov 19 '18 at 17:58






                            That's the best answer so far, since it adds a toast, which survives view switches. Having made it Swift 4 like and let it disappear, once a new toast is posted. Will add this as answer
                            – decades
                            Nov 19 '18 at 17:58














                            thanks. please upvote if you like the answer.
                            – Suhit Patil
                            Nov 19 '18 at 18:05




                            thanks. please upvote if you like the answer.
                            – Suhit Patil
                            Nov 19 '18 at 18:05












                            @decades updated for swift 4
                            – Suhit Patil
                            Nov 19 '18 at 18:24




                            @decades updated for swift 4
                            – Suhit Patil
                            Nov 19 '18 at 18:24












                            Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                            – decades
                            Nov 20 '18 at 19:20




                            Meanwhile I have improved it a bit (made it ready to remove an existing toast, to adapt to the textsize etc.) I will post the new version soon
                            – decades
                            Nov 20 '18 at 19:20











                            0














                            There is a 3rd party library that supports customizable toast notification with single line of code. Here is a simple example of it:



                            import Toast_Swift

                            ...

                            // basic usage
                            self.view.makeToast("This is a piece of toast")

                            // toast with a specific duration and position
                            self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)


                            Toast Swift library



                            Or else,



                            If you want to implement by your own. Use below code.



                            let toastLabel = UILabel(frame: CGRectMake(self.view.frame.size.width/2 - 150, self.view.frame.size.height-100, 300, 35))
                            toastLabel.backgroundColor = UIColor.blackColor()
                            toastLabel.textColor = UIColor.whiteColor()
                            toastLabel.textAlignment = NSTextAlignment.Center;
                            self.view.addSubview(toastLabel)
                            toastLabel.text = "hello man..."
                            toastLabel.alpha = 1.0
                            toastLabel.layer.cornerRadius = 10;
                            toastLabel.clipsToBounds = true
                            UIView.animateWithDuration(4.0, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                            toastLabel.alpha = 0.0

                            })





                            share|improve this answer





















                            • This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                              – decades
                              Nov 19 '18 at 18:02
















                            0














                            There is a 3rd party library that supports customizable toast notification with single line of code. Here is a simple example of it:



                            import Toast_Swift

                            ...

                            // basic usage
                            self.view.makeToast("This is a piece of toast")

                            // toast with a specific duration and position
                            self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)


                            Toast Swift library



                            Or else,



                            If you want to implement by your own. Use below code.



                            let toastLabel = UILabel(frame: CGRectMake(self.view.frame.size.width/2 - 150, self.view.frame.size.height-100, 300, 35))
                            toastLabel.backgroundColor = UIColor.blackColor()
                            toastLabel.textColor = UIColor.whiteColor()
                            toastLabel.textAlignment = NSTextAlignment.Center;
                            self.view.addSubview(toastLabel)
                            toastLabel.text = "hello man..."
                            toastLabel.alpha = 1.0
                            toastLabel.layer.cornerRadius = 10;
                            toastLabel.clipsToBounds = true
                            UIView.animateWithDuration(4.0, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                            toastLabel.alpha = 0.0

                            })





                            share|improve this answer





















                            • This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                              – decades
                              Nov 19 '18 at 18:02














                            0












                            0








                            0






                            There is a 3rd party library that supports customizable toast notification with single line of code. Here is a simple example of it:



                            import Toast_Swift

                            ...

                            // basic usage
                            self.view.makeToast("This is a piece of toast")

                            // toast with a specific duration and position
                            self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)


                            Toast Swift library



                            Or else,



                            If you want to implement by your own. Use below code.



                            let toastLabel = UILabel(frame: CGRectMake(self.view.frame.size.width/2 - 150, self.view.frame.size.height-100, 300, 35))
                            toastLabel.backgroundColor = UIColor.blackColor()
                            toastLabel.textColor = UIColor.whiteColor()
                            toastLabel.textAlignment = NSTextAlignment.Center;
                            self.view.addSubview(toastLabel)
                            toastLabel.text = "hello man..."
                            toastLabel.alpha = 1.0
                            toastLabel.layer.cornerRadius = 10;
                            toastLabel.clipsToBounds = true
                            UIView.animateWithDuration(4.0, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                            toastLabel.alpha = 0.0

                            })





                            share|improve this answer












                            There is a 3rd party library that supports customizable toast notification with single line of code. Here is a simple example of it:



                            import Toast_Swift

                            ...

                            // basic usage
                            self.view.makeToast("This is a piece of toast")

                            // toast with a specific duration and position
                            self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)


                            Toast Swift library



                            Or else,



                            If you want to implement by your own. Use below code.



                            let toastLabel = UILabel(frame: CGRectMake(self.view.frame.size.width/2 - 150, self.view.frame.size.height-100, 300, 35))
                            toastLabel.backgroundColor = UIColor.blackColor()
                            toastLabel.textColor = UIColor.whiteColor()
                            toastLabel.textAlignment = NSTextAlignment.Center;
                            self.view.addSubview(toastLabel)
                            toastLabel.text = "hello man..."
                            toastLabel.alpha = 1.0
                            toastLabel.layer.cornerRadius = 10;
                            toastLabel.clipsToBounds = true
                            UIView.animateWithDuration(4.0, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                            toastLabel.alpha = 0.0

                            })






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 2 '17 at 6:31









                            Sivajee Battina

                            2,9441831




                            2,9441831












                            • This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                              – decades
                              Nov 19 '18 at 18:02


















                            • This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                              – decades
                              Nov 19 '18 at 18:02
















                            This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                            – decades
                            Nov 19 '18 at 18:02




                            This library doesn't work if the holding view disappears in favour of a new view. The toast disappears too. This is not Android like. The only solution is to make the toast a child of the main window, not the view. But this is a problem of nearly all Toast libs out...
                            – decades
                            Nov 19 '18 at 18:02











                            0














                            This is best library I used for showing Toast in iOS apps same as android.



                            It also has pod support and pod name is pod 'Toast'



                            And implementation is so simple like



                            #import <UIView+Toast.h>


                            in your ViewController and then following line wherever you want to show it



                            [self.view makeToast:@"YOUR TOAST MESSAGE" duration:TOAST_TIMEOUT position:TOAST_CENTER];


                            Value for above keys are



                            #define TOAST_TOP @"CSToastPositionTop"
                            #define TOAST_CENTER @"CSToastPositionCenter"
                            #define TOAST_BOTTOM @"CSToastPositionBottom"
                            #define TOAST_TIMEOUT 2.0





                            share|improve this answer





















                            • No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                              – decades
                              Nov 20 '18 at 19:26
















                            0














                            This is best library I used for showing Toast in iOS apps same as android.



                            It also has pod support and pod name is pod 'Toast'



                            And implementation is so simple like



                            #import <UIView+Toast.h>


                            in your ViewController and then following line wherever you want to show it



                            [self.view makeToast:@"YOUR TOAST MESSAGE" duration:TOAST_TIMEOUT position:TOAST_CENTER];


                            Value for above keys are



                            #define TOAST_TOP @"CSToastPositionTop"
                            #define TOAST_CENTER @"CSToastPositionCenter"
                            #define TOAST_BOTTOM @"CSToastPositionBottom"
                            #define TOAST_TIMEOUT 2.0





                            share|improve this answer





















                            • No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                              – decades
                              Nov 20 '18 at 19:26














                            0












                            0








                            0






                            This is best library I used for showing Toast in iOS apps same as android.



                            It also has pod support and pod name is pod 'Toast'



                            And implementation is so simple like



                            #import <UIView+Toast.h>


                            in your ViewController and then following line wherever you want to show it



                            [self.view makeToast:@"YOUR TOAST MESSAGE" duration:TOAST_TIMEOUT position:TOAST_CENTER];


                            Value for above keys are



                            #define TOAST_TOP @"CSToastPositionTop"
                            #define TOAST_CENTER @"CSToastPositionCenter"
                            #define TOAST_BOTTOM @"CSToastPositionBottom"
                            #define TOAST_TIMEOUT 2.0





                            share|improve this answer












                            This is best library I used for showing Toast in iOS apps same as android.



                            It also has pod support and pod name is pod 'Toast'



                            And implementation is so simple like



                            #import <UIView+Toast.h>


                            in your ViewController and then following line wherever you want to show it



                            [self.view makeToast:@"YOUR TOAST MESSAGE" duration:TOAST_TIMEOUT position:TOAST_CENTER];


                            Value for above keys are



                            #define TOAST_TOP @"CSToastPositionTop"
                            #define TOAST_CENTER @"CSToastPositionCenter"
                            #define TOAST_BOTTOM @"CSToastPositionBottom"
                            #define TOAST_TIMEOUT 2.0






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 2 '17 at 10:15









                            Pushkraj

                            1,6451425




                            1,6451425












                            • No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                              – decades
                              Nov 20 '18 at 19:26


















                            • No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                              – decades
                              Nov 20 '18 at 19:26
















                            No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                            – decades
                            Nov 20 '18 at 19:26




                            No, it is not. You will notice once you switch a view with a toast open... Best solution (of all) see Suit below.
                            – decades
                            Nov 20 '18 at 19:26











                            0














                            there is no ThostView in iOS. we Can custom are use 3rd party libraries.
                            follow this link -




                            • https://github.com/scalessec/Toast-Swift






                            share|improve this answer


























                              0














                              there is no ThostView in iOS. we Can custom are use 3rd party libraries.
                              follow this link -




                              • https://github.com/scalessec/Toast-Swift






                              share|improve this answer
























                                0












                                0








                                0






                                there is no ThostView in iOS. we Can custom are use 3rd party libraries.
                                follow this link -




                                • https://github.com/scalessec/Toast-Swift






                                share|improve this answer












                                there is no ThostView in iOS. we Can custom are use 3rd party libraries.
                                follow this link -




                                • https://github.com/scalessec/Toast-Swift







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 2 '17 at 11:03









                                Sai Kumar

                                122




                                122























                                    0














                                    An attempt to make Suhit Pal's answer above Swift 4 like with a way to remove an existing Toast once a new appears



                                    extension UIView {

                                    private static var toastView: UILabel? = nil

                                    func displayToast(message : String, duration: Double? = 3.0) -> Void {
                                    if UIView.toastView != nil {
                                    UIView.toastView!.removeFromSuperview()
                                    }
                                    UIView.toastView = UILabel()
                                    UIView.toastView!.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                    UIView.toastView!.textColor = UIColor.white
                                    UIView.toastView!.textAlignment = .center
                                    UIView.toastView!.font = UIFont(name: "Font-name", size: 17)
                                    UIView.toastView!.layer.masksToBounds = true
                                    UIView.toastView!.layer.cornerRadius = 25
                                    UIView.toastView!.text = message
                                    UIView.toastView!.numberOfLines = 0
                                    UIView.toastView!.alpha = 0
                                    UIView.toastView!.translatesAutoresizingMaskIntoConstraints = false

                                    let window = UIApplication.shared.delegate?.window!
                                    window?.addSubview(UIView.toastView!)

                                    let horizontalCenterContraint : NSLayoutConstraint = NSLayoutConstraint(item: UIView.toastView!, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
                                    let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: UIView.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)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": UIView.toastView!])

                                    NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                    NSLayoutConstraint.activate(verticalContraint)

                                    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                    UIView.toastView!.alpha = 1
                                    }, completion: nil)

                                    DispatchQueue.main.asyncAfter(deadline: .now() + duration!) {
                                    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                    UIView.toastView!.alpha = 0
                                    }, completion: { (_) in
                                    UIView.toastView!.removeFromSuperview()
                                    })
                                    }
                                    }
                                    }





                                    share|improve this answer


























                                      0














                                      An attempt to make Suhit Pal's answer above Swift 4 like with a way to remove an existing Toast once a new appears



                                      extension UIView {

                                      private static var toastView: UILabel? = nil

                                      func displayToast(message : String, duration: Double? = 3.0) -> Void {
                                      if UIView.toastView != nil {
                                      UIView.toastView!.removeFromSuperview()
                                      }
                                      UIView.toastView = UILabel()
                                      UIView.toastView!.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                      UIView.toastView!.textColor = UIColor.white
                                      UIView.toastView!.textAlignment = .center
                                      UIView.toastView!.font = UIFont(name: "Font-name", size: 17)
                                      UIView.toastView!.layer.masksToBounds = true
                                      UIView.toastView!.layer.cornerRadius = 25
                                      UIView.toastView!.text = message
                                      UIView.toastView!.numberOfLines = 0
                                      UIView.toastView!.alpha = 0
                                      UIView.toastView!.translatesAutoresizingMaskIntoConstraints = false

                                      let window = UIApplication.shared.delegate?.window!
                                      window?.addSubview(UIView.toastView!)

                                      let horizontalCenterContraint : NSLayoutConstraint = NSLayoutConstraint(item: UIView.toastView!, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
                                      let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: UIView.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)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": UIView.toastView!])

                                      NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                      NSLayoutConstraint.activate(verticalContraint)

                                      UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                      UIView.toastView!.alpha = 1
                                      }, completion: nil)

                                      DispatchQueue.main.asyncAfter(deadline: .now() + duration!) {
                                      UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                      UIView.toastView!.alpha = 0
                                      }, completion: { (_) in
                                      UIView.toastView!.removeFromSuperview()
                                      })
                                      }
                                      }
                                      }





                                      share|improve this answer
























                                        0












                                        0








                                        0






                                        An attempt to make Suhit Pal's answer above Swift 4 like with a way to remove an existing Toast once a new appears



                                        extension UIView {

                                        private static var toastView: UILabel? = nil

                                        func displayToast(message : String, duration: Double? = 3.0) -> Void {
                                        if UIView.toastView != nil {
                                        UIView.toastView!.removeFromSuperview()
                                        }
                                        UIView.toastView = UILabel()
                                        UIView.toastView!.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                        UIView.toastView!.textColor = UIColor.white
                                        UIView.toastView!.textAlignment = .center
                                        UIView.toastView!.font = UIFont(name: "Font-name", size: 17)
                                        UIView.toastView!.layer.masksToBounds = true
                                        UIView.toastView!.layer.cornerRadius = 25
                                        UIView.toastView!.text = message
                                        UIView.toastView!.numberOfLines = 0
                                        UIView.toastView!.alpha = 0
                                        UIView.toastView!.translatesAutoresizingMaskIntoConstraints = false

                                        let window = UIApplication.shared.delegate?.window!
                                        window?.addSubview(UIView.toastView!)

                                        let horizontalCenterContraint : NSLayoutConstraint = NSLayoutConstraint(item: UIView.toastView!, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
                                        let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: UIView.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)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": UIView.toastView!])

                                        NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                        NSLayoutConstraint.activate(verticalContraint)

                                        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                        UIView.toastView!.alpha = 1
                                        }, completion: nil)

                                        DispatchQueue.main.asyncAfter(deadline: .now() + duration!) {
                                        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                        UIView.toastView!.alpha = 0
                                        }, completion: { (_) in
                                        UIView.toastView!.removeFromSuperview()
                                        })
                                        }
                                        }
                                        }





                                        share|improve this answer












                                        An attempt to make Suhit Pal's answer above Swift 4 like with a way to remove an existing Toast once a new appears



                                        extension UIView {

                                        private static var toastView: UILabel? = nil

                                        func displayToast(message : String, duration: Double? = 3.0) -> Void {
                                        if UIView.toastView != nil {
                                        UIView.toastView!.removeFromSuperview()
                                        }
                                        UIView.toastView = UILabel()
                                        UIView.toastView!.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                        UIView.toastView!.textColor = UIColor.white
                                        UIView.toastView!.textAlignment = .center
                                        UIView.toastView!.font = UIFont(name: "Font-name", size: 17)
                                        UIView.toastView!.layer.masksToBounds = true
                                        UIView.toastView!.layer.cornerRadius = 25
                                        UIView.toastView!.text = message
                                        UIView.toastView!.numberOfLines = 0
                                        UIView.toastView!.alpha = 0
                                        UIView.toastView!.translatesAutoresizingMaskIntoConstraints = false

                                        let window = UIApplication.shared.delegate?.window!
                                        window?.addSubview(UIView.toastView!)

                                        let horizontalCenterContraint : NSLayoutConstraint = NSLayoutConstraint(item: UIView.toastView!, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
                                        let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: UIView.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)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": UIView.toastView!])

                                        NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                        NSLayoutConstraint.activate(verticalContraint)

                                        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                        UIView.toastView!.alpha = 1
                                        }, completion: nil)

                                        DispatchQueue.main.asyncAfter(deadline: .now() + duration!) {
                                        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                        UIView.toastView!.alpha = 0
                                        }, completion: { (_) in
                                        UIView.toastView!.removeFromSuperview()
                                        })
                                        }
                                        }
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 19 '18 at 18:00









                                        decades

                                        3311020




                                        3311020























                                            0














                                            Here is my latest version of this. It allows to cancel an existing toast by just pushing a new. It also allows to provide an optional "reverseColors" parameter, which writes white on black instead default black on white. The toast adapts to the text size with a little margin left and right.



                                            extension UIView {

                                            private static var toastView: UILabel? = nil
                                            private static var toastViewCancelTask : DispatchWorkItem?

                                            func displayToast(message : String, duration: Double, reverseColors: Bool? = false) -> Void {
                                            if UIView.toastView != nil {
                                            UIView.toastView!.removeFromSuperview()
                                            UIView.toastViewCancelTask?.cancel()
                                            }


                                            UIView.toastView = UILabel()
                                            UIView.toastViewCancelTask = DispatchWorkItem {
                                            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                            UIView.toastView!.alpha = 0
                                            }, completion: { (_) in
                                            UIView.toastView!.removeFromSuperview()
                                            })
                                            }

                                            let toastView = UIView.toastView!
                                            print(message)

                                            if reverseColors != nil && reverseColors! {
                                            toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                            toastView.textColor = UIColor.white
                                            }
                                            else {
                                            toastView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
                                            toastView.textColor = UIColor.black
                                            }
                                            toastView.textAlignment = .center
                                            toastView.font = UIFont.systemFont(ofSize: 17)
                                            toastView.layer.masksToBounds = true
                                            toastView.layer.cornerRadius = 12
                                            toastView.text = message
                                            toastView.numberOfLines = 0
                                            toastView.alpha = 0
                                            toastView.sizeToFit()
                                            toastView.translatesAutoresizingMaskIntoConstraints = false

                                            let width = toastView.frame.size.width + 100 > self.frame.size.width ? self.frame.size.width - 100 : toastView.frame.size.width + 100

                                            let window = UIApplication.shared.delegate?.window!
                                            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: width )
                                            let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-30-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

                                            NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                            NSLayoutConstraint.activate(verticalContraint)

                                            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                            toastView.alpha = 0.8
                                            }, completion: nil)

                                            DispatchQueue.main.asyncAfter(deadline: .now() + duration , execute: UIView.toastViewCancelTask!)
                                            }

                                            }





                                            share|improve this answer


























                                              0














                                              Here is my latest version of this. It allows to cancel an existing toast by just pushing a new. It also allows to provide an optional "reverseColors" parameter, which writes white on black instead default black on white. The toast adapts to the text size with a little margin left and right.



                                              extension UIView {

                                              private static var toastView: UILabel? = nil
                                              private static var toastViewCancelTask : DispatchWorkItem?

                                              func displayToast(message : String, duration: Double, reverseColors: Bool? = false) -> Void {
                                              if UIView.toastView != nil {
                                              UIView.toastView!.removeFromSuperview()
                                              UIView.toastViewCancelTask?.cancel()
                                              }


                                              UIView.toastView = UILabel()
                                              UIView.toastViewCancelTask = DispatchWorkItem {
                                              UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                              UIView.toastView!.alpha = 0
                                              }, completion: { (_) in
                                              UIView.toastView!.removeFromSuperview()
                                              })
                                              }

                                              let toastView = UIView.toastView!
                                              print(message)

                                              if reverseColors != nil && reverseColors! {
                                              toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                              toastView.textColor = UIColor.white
                                              }
                                              else {
                                              toastView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
                                              toastView.textColor = UIColor.black
                                              }
                                              toastView.textAlignment = .center
                                              toastView.font = UIFont.systemFont(ofSize: 17)
                                              toastView.layer.masksToBounds = true
                                              toastView.layer.cornerRadius = 12
                                              toastView.text = message
                                              toastView.numberOfLines = 0
                                              toastView.alpha = 0
                                              toastView.sizeToFit()
                                              toastView.translatesAutoresizingMaskIntoConstraints = false

                                              let width = toastView.frame.size.width + 100 > self.frame.size.width ? self.frame.size.width - 100 : toastView.frame.size.width + 100

                                              let window = UIApplication.shared.delegate?.window!
                                              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: width )
                                              let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-30-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

                                              NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                              NSLayoutConstraint.activate(verticalContraint)

                                              UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                              toastView.alpha = 0.8
                                              }, completion: nil)

                                              DispatchQueue.main.asyncAfter(deadline: .now() + duration , execute: UIView.toastViewCancelTask!)
                                              }

                                              }





                                              share|improve this answer
























                                                0












                                                0








                                                0






                                                Here is my latest version of this. It allows to cancel an existing toast by just pushing a new. It also allows to provide an optional "reverseColors" parameter, which writes white on black instead default black on white. The toast adapts to the text size with a little margin left and right.



                                                extension UIView {

                                                private static var toastView: UILabel? = nil
                                                private static var toastViewCancelTask : DispatchWorkItem?

                                                func displayToast(message : String, duration: Double, reverseColors: Bool? = false) -> Void {
                                                if UIView.toastView != nil {
                                                UIView.toastView!.removeFromSuperview()
                                                UIView.toastViewCancelTask?.cancel()
                                                }


                                                UIView.toastView = UILabel()
                                                UIView.toastViewCancelTask = DispatchWorkItem {
                                                UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                                UIView.toastView!.alpha = 0
                                                }, completion: { (_) in
                                                UIView.toastView!.removeFromSuperview()
                                                })
                                                }

                                                let toastView = UIView.toastView!
                                                print(message)

                                                if reverseColors != nil && reverseColors! {
                                                toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                                toastView.textColor = UIColor.white
                                                }
                                                else {
                                                toastView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
                                                toastView.textColor = UIColor.black
                                                }
                                                toastView.textAlignment = .center
                                                toastView.font = UIFont.systemFont(ofSize: 17)
                                                toastView.layer.masksToBounds = true
                                                toastView.layer.cornerRadius = 12
                                                toastView.text = message
                                                toastView.numberOfLines = 0
                                                toastView.alpha = 0
                                                toastView.sizeToFit()
                                                toastView.translatesAutoresizingMaskIntoConstraints = false

                                                let width = toastView.frame.size.width + 100 > self.frame.size.width ? self.frame.size.width - 100 : toastView.frame.size.width + 100

                                                let window = UIApplication.shared.delegate?.window!
                                                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: width )
                                                let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-30-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

                                                NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                                NSLayoutConstraint.activate(verticalContraint)

                                                UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                                toastView.alpha = 0.8
                                                }, completion: nil)

                                                DispatchQueue.main.asyncAfter(deadline: .now() + duration , execute: UIView.toastViewCancelTask!)
                                                }

                                                }





                                                share|improve this answer












                                                Here is my latest version of this. It allows to cancel an existing toast by just pushing a new. It also allows to provide an optional "reverseColors" parameter, which writes white on black instead default black on white. The toast adapts to the text size with a little margin left and right.



                                                extension UIView {

                                                private static var toastView: UILabel? = nil
                                                private static var toastViewCancelTask : DispatchWorkItem?

                                                func displayToast(message : String, duration: Double, reverseColors: Bool? = false) -> Void {
                                                if UIView.toastView != nil {
                                                UIView.toastView!.removeFromSuperview()
                                                UIView.toastViewCancelTask?.cancel()
                                                }


                                                UIView.toastView = UILabel()
                                                UIView.toastViewCancelTask = DispatchWorkItem {
                                                UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                                UIView.toastView!.alpha = 0
                                                }, completion: { (_) in
                                                UIView.toastView!.removeFromSuperview()
                                                })
                                                }

                                                let toastView = UIView.toastView!
                                                print(message)

                                                if reverseColors != nil && reverseColors! {
                                                toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
                                                toastView.textColor = UIColor.white
                                                }
                                                else {
                                                toastView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
                                                toastView.textColor = UIColor.black
                                                }
                                                toastView.textAlignment = .center
                                                toastView.font = UIFont.systemFont(ofSize: 17)
                                                toastView.layer.masksToBounds = true
                                                toastView.layer.cornerRadius = 12
                                                toastView.text = message
                                                toastView.numberOfLines = 0
                                                toastView.alpha = 0
                                                toastView.sizeToFit()
                                                toastView.translatesAutoresizingMaskIntoConstraints = false

                                                let width = toastView.frame.size.width + 100 > self.frame.size.width ? self.frame.size.width - 100 : toastView.frame.size.width + 100

                                                let window = UIApplication.shared.delegate?.window!
                                                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: width )
                                                let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-30-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

                                                NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
                                                NSLayoutConstraint.activate(verticalContraint)

                                                UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                                                toastView.alpha = 0.8
                                                }, completion: nil)

                                                DispatchQueue.main.asyncAfter(deadline: .now() + duration , execute: UIView.toastViewCancelTask!)
                                                }

                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 20 '18 at 19:25









                                                decades

                                                3311020




                                                3311020






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41422251%2fhow-to-add-android-like-toast-in-ios%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Create new schema in PostgreSQL using DBeaver

                                                    Deepest pit of an array with Javascript: test on Codility

                                                    Costa Masnaga