37

Does anyone know what the Java Toast equivalent of this iOS Objective C event would be in a Fragment? Below is a sample of what I have written in iOS. What I am looking for the same Alert in Java using a Toast in place of the iOS UIAlert. I am sorry if I did not make that clear on my original post.

- (void) dateLogic {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM dd"];
    NSString *theDate = [dateFormat stringFromDate:[NSDate date]];

    //JANUARY
    if ([theDate isEqualToString:@"January 01"]) {

        feastDay = [[UIAlertView alloc]
                     initWithTitle:@"New Years Day!"
                     message:@"January 01"
                     delegate:self
                     cancelButtonTitle:nil
                     otherButtonTitles:@"Close", nil];
        feastDay.delegate = self;
        [feastDay show];
    }
}
Enrique Bermúdez
  • 1,740
  • 2
  • 11
  • 25
Bil Kimes
  • 371
  • 1
  • 3
  • 5
  • Possible duplicate of [Displaying a message in iOS which has the same functionality as Toast in Android](http://stackoverflow.com/questions/18680891/displaying-a-message-in-ios-which-has-the-same-functionality-as-toast-in-android) – noelicus Mar 20 '17 at 13:18

19 Answers19

32

I found this amazing class in github that works like a charm. Toast for iOS It is enough to import the UIView+Toast.h and UIView+Toast.m files and then add

[self.view makeToast:@"This is a piece of toast."];

as written in the page examples.

Lucia Belardinelli
  • 727
  • 1
  • 11
  • 20
13

I handled it with a simple static UI Helper method using the Key Window:

+(void)displayToastWithMessage:(NSString *)toastMessage
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
        UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
        UILabel *toastView = [[UILabel alloc] init];
        toastView.text = toastMessage;
        toastView.font = [MYUIStyles getToastHeaderFont];
        toastView.textColor = [MYUIStyles getToastTextColor];
        toastView.backgroundColor = [[MYUIStyles getToastBackgroundColor] colorWithAlphaComponent:0.9];
        toastView.textAlignment = NSTextAlignmentCenter;
        toastView.frame = CGRectMake(0.0, 0.0, keyWindow.frame.size.width/2.0, 100.0);
        toastView.layer.cornerRadius = 10;
        toastView.layer.masksToBounds = YES;
        toastView.center = keyWindow.center;

        [keyWindow addSubview:toastView];

        [UIView animateWithDuration: 3.0f
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations: ^{
                         toastView.alpha = 0.0;
                     }
                     completion: ^(BOOL finished) {
                         [toastView removeFromSuperview];
                     }
         ];
    }];
}
wboland
  • 139
  • 1
  • 2
12

There is no android toast equivalent in iOS.

But there are always workarounds like

you can animate a view and play with its alpha

The below is just sample code not a solution

UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:3.0f];
imageView.alpha = 0.0f;
[UIView commitAnimations];

if you dont want to slowly fade within 3 seconds, you can use

[UIView setAnimationDelay:3];

and reduce the animation duraction to 0.5f or something. i think using a short fade out time feels better than just simply set hide to YES

Vivo
  • 768
  • 1
  • 8
  • 20
11

We've implemented something like this in our open source library Raisin Toast. Setup is quite straightforward once you add the files to your project:

Add a property to your app delegate:

@property (strong, nonatomic) RZMessagingWindow *errorWindow;

Create the default messaging window:

self.errorWindow = [RZMessagingWindow defaultMessagingWindow];
[RZErrorMessenger setDefaultMessagingWindow:self.errorWindow];

and then one line to present the messaging window:

[RZErrorMessenger displayErrorWithTitle:@"Whoops!" detail:@"Something went horribly wrong and we accidentally cut off the wrong leg"];

The demo project highlights some of the more advanced customizations of adding images and custom styles.

The implementation uses a second UIWindow and because of the RZErrorMessenger class method it's available everywhere.

earnshavian
  • 1,864
  • 2
  • 13
  • 17
10

Maybe this can help someone:

NSString *message = @"Toast kind of message";
UIAlertView *toast = [[UIAlertView alloc] initWithTitle:nil
                                            message:message
                                           delegate:nil
                                  cancelButtonTitle:nil
                                  otherButtonTitles:nil, nil];
[toast show];
int duration = 1; // in seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[toast dismissWithClickedButtonIndex:0 animated:YES];
});

UPDATE UIAlertView is deprecated in IOS 8. Here the new way:

NSString *message = @"Toast kind of message";

UIAlertController *toast =[UIAlertController alertControllerWithTitle:nil
 message:message 
 preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:toast animated:YES completion:nil];

int duration = 1; // in seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [toast dismissViewControllerAnimated:YES completion:nil];
});

EDIT: For the ones that using Xamarin.IOS you can do like this:

new UIAlertView(null, message, null, "OK", null).Show();

using UIKit; is required.

Daniele D.
  • 2,624
  • 3
  • 36
  • 42
4

A Swift 3 solution ready for copy paste:

import UIKit

public extension UIView {

    public func showToast(message:String, duration:Int = 2000) {

        let toastLabel = UIPaddingLabel();
        toastLabel.padding = 10;
        toastLabel.translatesAutoresizingMaskIntoConstraints = false;
        toastLabel.backgroundColor = UIColor.darkGray;
        toastLabel.textColor = UIColor.white;
        toastLabel.textAlignment = .center;
        toastLabel.text = message;
        toastLabel.numberOfLines = 0;
        toastLabel.alpha = 0.9;
        toastLabel.layer.cornerRadius = 20;
        toastLabel.clipsToBounds = true;

        self.addSubview(toastLabel);

        self.addConstraint(NSLayoutConstraint(item:toastLabel, attribute:.left, relatedBy:.greaterThanOrEqual, toItem:self, attribute:.left, multiplier:1, constant:20));
        self.addConstraint(NSLayoutConstraint(item:toastLabel, attribute:.right, relatedBy:.lessThanOrEqual, toItem:self, attribute:.right, multiplier:1, constant:-20));
        self.addConstraint(NSLayoutConstraint(item:toastLabel, attribute:.bottom, relatedBy:.equal, toItem:self, attribute:.bottom, multiplier:1, constant:-20));
        self.addConstraint(NSLayoutConstraint(item:toastLabel, attribute:.centerX, relatedBy:.equal, toItem:self, attribute:.centerX, multiplier:1, constant:0));

        UIView.animate(withDuration:0.5, delay:Double(duration) / 1000.0, options:[], animations: {

            toastLabel.alpha = 0.0;

        }) { (Bool) in

            toastLabel.removeFromSuperview();
        }
    }
}

The UIPaddingLabel class:

import UIKit

@IBDesignable class UIPaddingLabel: UILabel {

    private var _padding:CGFloat = 0.0;

    public var padding:CGFloat {

        get { return _padding; }
        set {
            _padding = newValue;

            paddingTop = _padding;
            paddingLeft = _padding;
            paddingBottom = _padding;
            paddingRight = _padding;
        }
    }

    @IBInspectable var paddingTop:CGFloat = 0.0;
    @IBInspectable var paddingLeft:CGFloat = 0.0;
    @IBInspectable var paddingBottom:CGFloat = 0.0;
    @IBInspectable var paddingRight:CGFloat = 0.0;

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top:paddingTop, left:paddingLeft, bottom:paddingBottom, right:paddingRight);
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets));
    }

    override var intrinsicContentSize: CGSize {

        get {
            var intrinsicSuperViewContentSize = super.intrinsicContentSize;
            intrinsicSuperViewContentSize.height += paddingTop + paddingBottom;
            intrinsicSuperViewContentSize.width += paddingLeft + paddingRight;
            return intrinsicSuperViewContentSize;
        }
    }
}
Tim Autin
  • 6,043
  • 5
  • 46
  • 76
3

Swift 2.0:

Use https://github.com/Rannie/Toast-Swift/blob/master/SwiftToastDemo/Toast/HRToast%2BUIView.swift .

Download the HRToast + UIView.swift class and drag and drop to project. Make sure you check 'copy items if needed' on dialogue box.

  //Usage:
  self.view.makeToast(message: "Simple Toast")
  self.view.makeToast(message: "Simple Toast", duration: 2.0, position:HRToastPositionTop)

  self.view.makeToast(message: "Simple Toast", duration: 2.0, position: HRToastPositionCenter, image: UIImage(named: "ic_120x120")!)

  self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionDefault, title: "Simple Toast")

  self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionCenter, title: "Simple Toast", image: UIImage(named: "ic_120x120")!)

  self.view.makeToastActivity()
  self.view.makeToastActivity(position: HRToastPositionCenter)
  self.view.makeToastActivity(position: HRToastPositionDefault, message: "Loading")
  self.view.makeToastActivityWithMessage(message: "Loading")
Alvin George
  • 14,148
  • 92
  • 64
2

I decided to put apart a more complete Xamarin.iOS / MonoTouch solution that works great for me.

    private async Task ShowToast(string message, UIAlertView toast = null)
    {
        if (null == toast)
        {
            toast = new UIAlertView(null, message, null, null, null);
            toast.Show();
            await Task.Delay(2000);
            await ShowToast(message, toast);
            return;
        }

        UIView.BeginAnimations("");
        toast.Alpha = 0;
        UIView.CommitAnimations();
        toast.DismissWithClickedButtonIndex(0, true);
    }

UPDATE UIAlertView is deprecated in IOS 8. Here the new way:

var toast = UIAlertController.Create("", message, UIAlertControllerStyle.Alert);
        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(toast, true, async () =>
        {
            await Task.Delay(2000);
            UIView.BeginAnimations("");
            toast.View.Alpha = 0;
            UIView.CommitAnimations();
            toast.DismissViewController(true, null);
        });

If you want the toast at the bottom of the screen rather than in the middle use

UIAlertControllerStyle.ActionSheet

If the method is called from a background thread (not the main UI thread) then BeginInvokeOnMainThread is required which means just call it like this.

BeginInvokeOnMainThread(() =>
{
 ShowToast(message);
});
Daniele D.
  • 2,624
  • 3
  • 36
  • 42
1

If you really want just the android toast appearance then try out this library, it works well, have used within few of my apps

https://github.com/ecstasy2/toast-notifications-ios works well...

Geet
  • 2,427
  • 2
  • 21
  • 39
1

Objective C

+(void)showPositiveMessage :(NSString*)message{
[ViewController showAlertWithBackgroundColor:[UIColor greenColor] textColor:[UIColor whiteColor] message:message];}

+(void)showNegativeMessage :(NSString*)message{
    [ViewController showAlertWithBackgroundColor:[UIColor redColor] textColor:[UIColor whiteColor] message:message];}

+(void)showAlertWithBackgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor message:(NSString*)String{
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;

    UILabel* label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = String;
    label.font = [UIFont fontWithName:@"HelveticaNeue" size:FONTSIZE];
    label.adjustsFontSizeToFitWidth = true;
    [label sizeToFit];
    label.numberOfLines = 4;
    label.layer.shadowColor = [UIColor grayColor].CGColor;
    label.layer.shadowOffset = CGSizeMake(4, 3);
    label.layer.shadowOpacity = 0.3;
    label.frame = CGRectMake(320, 64, appDelegate.window.frame.size.width, 44);
    label.alpha = 1;        
    label.backgroundColor = backgroundColor;
    label.textColor = textColor;

    [appDelegate.window addSubview:label];

    CGRect basketTopFrame  = label.frame;
    basketTopFrame.origin.x = 0;


    [UIView animateWithDuration:2.0 delay:0.0 usingSpringWithDamping:0.5 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseOut animations: ^(void){
        label.frame = basketTopFrame;
    } completion:^(BOOL finished){
        [label removeFromSuperview];
    }
    ];}

Swift

How to Toast message in Swift?

Community
  • 1
  • 1
Yogesh Lolusare
  • 2,162
  • 1
  • 24
  • 35
1

I know this question is pretty old, but I found myself here wondering the same thing, and I found a solution, so I thought I would share. This method allows for the alert to be dismissed after a time delay set by you.

let alertController = UIAlertController(title: "Error", message: "There was a problem logging in, please try again", preferredStyle: UIAlertControllerStyle.alert)
self.present(alertController, animated: true, completion: nil)
let delay = DispatchTime.now() + 1 // change 1 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: delay) {
  // Your code with delay
  alertController.dismiss(animated: true, completion: nil)
}

If you get an error that crashes your app, it may be because the alertConroller is being run on a background thread. To fix this wrap your code in this:

DispatchQueue.main.async(execute: {

});

This method allows the message to be dismiss when the user clicks an "OK" button below the message

let alertController = UIAlertController(title: "Error", message: "There was a problem logging in, please try again", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
                    print("OK")
                }
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
Tyler Pashigian
  • 457
  • 4
  • 13
1

Daniele D has an elegant solution, but UIAlertView is deprecated. Use UIAlertController instead:

    NSString *message = @"Toast message.";

    UIAlertController *toast =[UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:toast animated:YES completion:nil];

    int duration = 2; // in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [toast dismissViewControllerAnimated:YES completion:nil];
    });
TomV
  • 1,157
  • 1
  • 13
  • 25
0

This one is quite handy as well since it has a completion block as well, please have a look :) https://github.com/PrajeetShrestha/EkToast

Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63
0

Another swift simple toast implementation. Single file, copy paste it into your app:

https://github.com/gglresearchanddevelopment/ios-toast

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
0

I have written the easiest code and it works always perfectly for me always.

add this line in Appdelegate.h

-(void) showToastMessage:(NSString *) message;

Add the below code in Appdelegate.m

-(void) showToastMessage:(NSString *) message
{

    //if there is already a toast message on the screen so that donot show and return from here only
    if ([self.window.rootViewController.view viewWithTag:100])
    {
        return;
    }

    UILabel *lblMessage = [[UILabel alloc]init];
    lblMessage.tag = 100;
    lblMessage.textAlignment = NSTextAlignmentCenter;
    lblMessage.text = message;
    lblMessage.font = [UIFont systemFontOfSize:12.0];
    lblMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5f];
    lblMessage.textColor = [UIColor whiteColor];

    CGSize textSize = [[lblMessage text] sizeWithAttributes:@{NSFontAttributeName:[lblMessage font]}];

    float x = self.window.rootViewController.view.center.x - textSize.width/2;
    float labelWidth = MIN(textSize.width, SCREEN_WIDTH - 40);

    lblMessage.frame = CGRectMake(x, SCREEN_HEIGHT - 90.f, labelWidth + 50, textSize.height + 20);
    CGRect oldFrame = lblMessage.frame;

    //comment this line if u don't want to show the toost message below in the screen
    lblMessage.center = self.window.rootViewController.view.center;
    x = lblMessage.frame.origin.x;
    lblMessage.frame = CGRectMake(x, oldFrame.origin.y, oldFrame.size.width, oldFrame.size.height);

    //and add this line if you want to show the message in the centre of the screen
    //lblMessage.center = self.window.rootViewController.view.center;

    lblMessage.layer.cornerRadius = lblMessage.frame.size.height/2;
    lblMessage.layer.masksToBounds = true;

    [self.window.rootViewController.view addSubview:lblMessage];
    [self performSelector:@selector(removeToastMessage:) withObject:lblMessage afterDelay:2.0f];

}


-(void) removeToastMessage: (UILabel *)label
{
    [UIView animateWithDuration:1.0f animations:^{
        label.alpha = 0.f;
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [label removeFromSuperview];

    });
}

Now in any ViewController you want to use just import the #import "AppDelegate.h"and use below code.

For showing toast message

AppDelegate *appDel = (AppDelegate *) [[UIApplication sharedApplication] delegate];
                     NSString *strMessage = @"show my alert";
                     [appDel showToastMessage:strMessage];
Yash
  • 171
  • 2
  • 8
0

Swift 4+

You don't need to download anything unless you are looking for some kind of extra functionality that UIAlertController won't give you.

let alertbox = UIAlertController(title: "Error", message: "You did not enter an email address", preferredStyle: UIAlertController.Style.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in
            print("OK")
        }
        alertbox.addAction(okAction)
        self.present(alertbox, animated: true, completion: nil)

The above code presents an alert dialog with the title "Error", the description message and then an OK button so the user can dismiss the alert.

Will Buffington
  • 1,048
  • 11
  • 13
0

This is the documentation : https://developer.apple.com/documentation/uikit/uialertcontroller

and the is an example to implament a class :

class AlertMode: NSObject {

  func alertWithOneAction(title: String, message: String, actionTitle: String, handler: @escaping ((UIAlertAction) -> Void), `on` controller: UIViewController ) -> () {
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: actionTitle, style: UIAlertActionStyle.default, handler: handler))
    controller.present(alert, animated: true, completion: nil)
 }
}
ironRoei
  • 2,049
  • 24
  • 45
0

For Swift UI, I use this open source: https://github.com/huynguyencong/ToastSwiftUI . It is easy to use.

struct ContentView: View {
    @State private var isShowingToast = false
    
    var body: some View {
        VStack(spacing: 20) {
            Button("Show toast") {
                self.isShowingToast = true
            }
            
            Spacer()
        }
        .padding()

        // Just add a modifier to show a toast, with binding variable to control
        .toast(isPresenting: $isShowingToast, dismissType: .after(3)) {
            ToastView(message: "Hello world!", icon: .info)
        }
    }
}
huynguyen
  • 7,616
  • 5
  • 35
  • 48
-1

You can use, i use this all the time, this works perfectly fine in objective c.

+(void)showToastOnView:(UIView * _Nonnull)view withString:(NSString * _Nonnull)text forDuration:(AVToastDurationStatus)duration;

provided here:

AviToast Github.

  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers) – Tunaki Feb 09 '17 at 08:01