2014-07-22 9 views
22

Qualcuno sa che l'equivalente Java Toast di questo evento dell'obiettivo C iOS sarebbe in un frammento? Di seguito è riportato un esempio di ciò che ho scritto su iOS. Quello che sto cercando per lo stesso avviso in Java utilizzando un Toast al posto del UIAlert iOS. Mi dispiace se non l'ho chiarito sul mio post originale.Equivalente Android Toast in iOS

- (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]; 
    } 
} 
+0

Eventuali duplicati di [Visualizzazione di un messaggio in iOS, che ha la stessa funzionalità Toast in Android] (http://stackoverflow.com/questions/18680891/displaying- a-message-in-ios-che-ha-stessa-funzionalità-come-toast-in-android) – noelicus

risposta

11

Non c'è nessun equivalente di Android su iOS.

Ma ci sono soluzioni alternative sempre come

è possibile animare una vista e giocare con la sua alfa

il seguito è solo il codice di esempio non è una soluzione

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

se non volete lentamente dissolvenza entro 3 secondi, è possibile utilizzare

[UIView setAnimationDelay:3]; 

e ridurre e durata dell'animazione a 0.5f o qualcosa del genere. Penso che con un breve tempo di Fade Out si sente meglio di nascondere solo impostare semplicemente SI

1

Se davvero si vuole solo l'aspetto brindisi Android poi, provare questa biblioteca, funziona bene, hanno utilizzato entro poche delle mie applicazioni

https://github.com/ecstasy2/toast-notifications-ios funziona bene ...

+0

Prova a postare parte del codice snippet.link non sono gradite le risposte – Venky

11

Abbiamo implementato qualcosa di simile nella nostra libreria open source Raisin Toast. L'installazione è molto semplice, una volta aggiunto i file al progetto:

Aggiungere una proprietà per la vostra applicazione delegato:

@property (strong, nonatomic) RZMessagingWindow *errorWindow; 

creare la finestra di messaggistica predefinito:

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

e poi una linea presenta la finestra di messaggistica:

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

Il progetto demo evidenzia alcuni dei e personalizzazioni avanzate per l'aggiunta di immagini e stili personalizzati.

L'implementazione utilizza una seconda UIWindow e, a causa del metodo di classe RZErrorMessenger, è disponibile ovunque.

11

ho gestita con un metodo semplice interfaccia utente Helper statico utilizzando la finestra chiave:

+(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]; 
        } 
     ]; 
    }]; 
} 
27

Ho trovato questa classe sorprendente in github che funziona come un fascino. Toast for iOS E 'sufficiente importare i file UIView + Toast.h e UIView + Toast.m e quindi aggiungere

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

come scritto negli esempi di pagina.

+2

Porta Swift della stessa libreria: https: //github.com/scalessec/Toast-Swift – user2393462435

+0

un toast dovrebbe essere indipendente da una vista. Se cambia UIViewController, il brindisi dovrebbe essere ancora visibile. – NikkyD

+0

perché non utilizzare la finestra dell'app? Vale a dire. UIApplication ... delgate.window? – makeroo

9

Forse questo può aiutare qualcuno:

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 è deprecato in IOS 8. Ecco il nuovo modo:

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: Per quelli che utilizzano Xamarin.IOS si può fare in questo modo:

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

utilizzando UIKit; è obbligatorio.

1

Ho deciso di mettere a parte una soluzione Xamarin.iOS/MonoTouch più completa che funziona perfettamente per 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); 
    } 

Se il metodo è chiamato da un filo di fondo (non thread UI principale) allora BeginInvokeOnMainThread è richiesto che significa basta chiamare così.

BeginInvokeOnMainThread(() => 
{ 
ShowToast(message); 
}); 
3

Swift 2.0:

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

Scaricare la classe HRToast + UIView.swift e trascinare la selezione sul progetto. Assicurati di selezionare 'copia elementi se necessario' nella finestra di dialogo.

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

1

A Swift 3 soluzione pronta per copia incolla:

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

La 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

È possibile utilizzare, io uso questo tutto il tempo, questo funziona perfettamente bene in Objective C.

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

fornito qui:

AviToast Github.

+0

Un collegamento a una soluzione è il benvenuto, ma per favore assicurati che la tua risposta sia utile senza di essa: [aggiungi contesto intorno al link] (// meta.stackexchange.com/a/8259) in modo che i tuoi utenti abbiano qualche idea di cosa sia e perché è lì, quindi cita la parte più pertinente della pagina a cui stai collegando nel caso in cui la pagina di destinazione non sia disponibile. [Le risposte che sono poco più di un collegamento possono essere eliminate.] (// stackoverflow.com/help/deleted-answers) – Tunaki

+0

Sebbene questo collegamento possa rispondere alla domanda, è meglio includere qui le parti essenziali della risposta e fornire il link per riferimento. Le risposte di solo collegamento possono diventare non valide se la pagina collegata cambia. - [Dalla recensione] (/ recensione/post di bassa qualità/15153110) – Molske

0

So che questa domanda è piuttosto vecchio, ma ho trovato me stesso qui a chiedermi la stessa cosa, e ho trovato una soluzione, così ho pensato che avrei condiviso. Questo metodo consente di chiudere l'avviso dopo un intervallo di tempo impostato dall'utente.

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

Se si ottiene un errore che blocca la vostra applicazione, può essere perché l'alertConroller viene eseguito su un thread in background. Per risolvere questo problema avvolgere il codice in questo modo:

DispatchQueue.main.async(execute: { 

}); 

Questo metodo consente il messaggio da respingere quando l'utente fa clic su un pulsante "OK" sotto il messaggio

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

Daniele D ha una soluzione elegante, ma UIAlertView è deprecato. Utilizzare invece UIAlertController:

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

Ho scritto il codice più semplice e funziona sempre perfettamente per me sempre.

aggiungere questa riga in Appdelegate.h

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

Aggiungere il codice qui sotto 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]; 

    }); 
} 

Ora in qualsiasi ViewController che si desidera utilizzare solo importare la #import "AppDelegate.h" e utilizzare sotto codice.

Per mostrare un messaggio brindisi

AppDelegate *appDel = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 
        NSString *strMessage = @"show my alert"; 
        [appDel showToastMessage:strMessage];