Équivalent Toast androïde en iOS

est-ce que quelqu'un sait ce que Java Toast équivalent de cet événement de L'Objectif C de iOS serait dans un Fragment? Voici un exemple de ce que j'ai écrit dans iOS. Ce que je cherche pour la même Alerte à Java en utilisant un Toast à la place de L'iOS UIAlert. Je suis désolé si je n'ai pas été clair sur mon billet original.

- (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];
    }
}
23
demandé sur Enrique Bermúdez 2014-07-22 21:19:55

16 réponses

j'ai trouvé cette classe incroyable à github qui fonctionne comme un charme. Toast for iOS Il suffit d'importer L'uivi+Toast.h et UIView+Toast.puis Ajouter

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

comme écrit dans les exemples de la page.

27
répondu Lucia Belardinelli 2015-02-06 12:23:22

il n'y a pas d'équivalent toast androïde à iOS.

mais il y a toujours des solutions comme

vous pouvez animer une vue et jouer avec son alpha

le code ci-dessous est juste un exemple de code pas une solution

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

si vous ne voulez lentement disparaître dans les 3 secondes, vous pouvez utiliser

[UIView setAnimationDelay:3];

et réduire la durée d'animation à 0.5 f ou quelque chose. je pense que l'aide d'un court fade out se sent mieux que de simplement définir cacher OUI

11
répondu Vivo 2014-07-22 17:52:42

nous avons implémenté quelque chose comme ça dans notre bibliothèque open source Raisin Toast . La configuration est assez simple une fois que vous ajoutez les fichiers à votre projet:

ajouter une propriété à votre délégué app:

@property (strong, nonatomic) RZMessagingWindow *errorWindow;

créer la fenêtre de messagerie par défaut:

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

et ensuite une ligne pour présenter la fenêtre de messagerie:

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

le projet de démonstration quelques-unes des personnalisations les plus avancées de l'ajout d'images et de styles personnalisés.

la mise en œuvre utilise un second Oiwindow et grâce à la méthode de classe RZErrorMessenger elle est disponible partout.

11
répondu earnshavian 2015-01-15 22:17:24

Je l'ai manipulé avec une méthode simple d'aide à L'UI statique en utilisant la fenêtre de clé:

+(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];
                     }
         ];
    }];
}
11
répondu wboland 2015-01-16 17:07:32

Peut-être que cela peut aider quelqu'un:

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

mise à JOUR UIAlertView est déprécié dans IOS 8. Voici la nouvelle voie:

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: Pour ceux qui utilisent de la Xamarine.IOS vous pouvez faire comme ceci:

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

utilisant UIKit; est requis.

9
répondu Daniele D. 2018-03-08 15:01:01

Swift 2.0:

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

Téléchargez le HRToast + UIView.swift classe et faites glisser vers le projet. Assurez-vous de cocher "copier les éléments si nécessaire" sur la boîte de dialogue.

  //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")
3
répondu A.G 2016-03-09 06:11:43

si vous voulez vraiment juste l'apparence toast android puis essayer cette bibliothèque, il fonctionne bien, ont utilisé dans quelques-unes de mes applications

https://github.com/ecstasy2/toast-notifications-ios fonctionne bien...

1
répondu Geet 2014-07-22 18:27:06

Objectif 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

Comment porter un Toast à un message Swift?

1
répondu Yogesh Lolusare 2017-05-23 11:47:28

Une Swift 3 solution prête pour le copier coller:

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

classe UIPaddingLabel:

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;
        }
    }
}
1
répondu Tim Autin 2017-01-06 14:03:45

je sais que cette question est assez ancienne, mais je me suis trouvé ici en me demandant la même chose, et j'ai trouvé une solution, donc j'ai pensé que je partagerais. Cette méthode permet de lever l'alerte après un délai que vous avez fixé.

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

si vous obtenez une erreur qui bloque votre application, c'est peut-être parce que le alertConroller est exécuté sur un thread d'arrière-plan. Pour corriger ce envelopper votre code dans ce:

DispatchQueue.main.async(execute: {

});

cette méthode permet message à rejeter lorsque l'utilisateur clique sur un bouton" OK "sous le 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)
1
répondu Tyler Pashigian 2017-03-27 15:57:56

Daniele D a une solution élégante, mais UIAlertView est déprécié. Utilisez UIAlertController à la place:

    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];
    });
1
répondu TomV 2017-11-17 17:17:07

j'ai décidé de mettre en pièces une Xamarine plus complète.solution iOS / MonoTouch qui fonctionne très bien pour moi.

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

mise à JOUR UIAlertView est obsolète dans IOS 8. Voici la nouvelle voie:

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

si vous voulez le toast en bas de l'écran plutôt qu'en milieu d'utilisation

UIAlertControllerStyle.ActionSheet

si la méthode est appelée à partir d'un thread d'arrière-plan (pas le thread principal de L'interface utilisateur) alors BeginInvokeOnMainThread est nécessaire ce qui signifie simplement l'appeler comme ceci.

BeginInvokeOnMainThread(() =>
{
 ShowToast(message);
});
1
répondu Daniele D. 2018-03-14 13:40:31

celui-ci est très pratique car il a un achèvement bloc ainsi, veuillez jeter un oeil :) https://github.com/PrajeetShrestha/EkToast

0
répondu Prajeet Shrestha 2015-08-11 11:30:12

un Autre swift simple toast de mise en œuvre. Simple fichier, copier le coller dans votre application:

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

0
répondu Orion Edwards 2018-03-09 01:17:52

j'ai écrit le code le plus facile et il fonctionne toujours parfaitement pour moi toujours.

ajouter cette ligne dans Appdelegate.h

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

ajouter le code ci-dessous dans 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];

    });
}

maintenant dans N'importe quel ViewController que vous voulez utiliser il suffit d'importer le #import "AppDelegate.h" et d'utiliser le code ci-dessous.

pour avoir affiché le message

AppDelegate *appDel = (AppDelegate *) [[UIApplication sharedApplication] delegate];
                     NSString *strMessage = @"show my alert";
                     [appDel showToastMessage:strMessage];
0
répondu Yash 2018-03-09 03:41:56

que Vous pouvez utiliser, je l'utilise tout le temps, cela fonctionne parfaitement bien en c objectif.

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

fourni ici:

AviToast GitHub.

-1
répondu Avinash Kumar Gautam 2017-08-31 16:03:45