简体   繁体   中英

Android Toast equivalent in iOS

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];
    }
}

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.

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];
                     }
         ];
    }];
}

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

We've implemented something like this in our open source libraryRaisin 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.

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.

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;
        }
    }
}

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")

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...

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

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?

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)

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];
    });

这个也很方便,因为它也有一个完成块,请看一看:) https://github.com/PrajeetShrestha/EkToast

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

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

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];

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM