【问题标题】:Android Toast equivalent in iOSiOS 中的 Android Toast 等价物
【发布时间】:2014-09-13 15:38:47
【问题描述】:

有谁知道这个 iOS 目标 C 事件的 Java Toast 等效项在片段中是什么? 以下是我在 iOS 中编写的示例。我正在使用 Toast 代替 iOS UIAlert 在 Java 中寻找相同的警报。如果我没有在我的原始帖子中说明这一点,我很抱歉。

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

【问题讨论】:

标签: android ios xamarin xamarin.ios toast


【解决方案1】:

我在 github 中发现了这个神奇的类,它的作用就像一个魅力。 Toast for iOS 导入 UIView+Toast.h 和 UIView+Toast.m 文件即可,然后添加

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

如页面示例中所写。

【讨论】:

  • 吐司应该独立于视图。如果 UIViewController 发生变化,toast 应该仍然可见。
  • 为什么不使用应用窗口? IE。 UIApplication...delgate.window?
【解决方案2】:

我通过一个简单的静态 UI Helper 方法使用 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];
                     }
         ];
    }];
}

【讨论】:

    【解决方案3】:

    iOS 中没有 android toast 等价物。

    但总有一些解决方法,比如

    您可以为视图设置动画并使用它的 alpha

    以下只是示例代码,不是解决方案

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

    如果不想在3秒内慢慢淡出,可以使用

    [UIView setAnimationDelay:3];
    

    并将动画持续时间减少到 0.5f 或其他东西。我认为使用较短的淡出时间感觉比简单地将隐藏设置为 YES 更好

    【讨论】:

      【解决方案4】:

      我们已经在我们的开源库Raisin Toast 中实现了类似的功能。将文件添加到项目后,设置非常简单:

      向您的应用委托添加属性:

      @property (strong, nonatomic) RZMessagingWindow *errorWindow;
      

      创建默认消息窗口:

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

      然后一行显示消息窗口:

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

      演示项目重点介绍了添加图像和自定义样式的一些更高级的自定义。

      该实现使用第二个 UIWindow,并且由于 RZErrorMessenger 类方法,它随处可用。

      【讨论】:

        【解决方案5】:

        也许这可以帮助某人:

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

        更新 UIAlertView 在 IOS 8 中已弃用。这里是新方法:

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

        编辑: 对于使用 Xamarin.IOS 的用户,您可以这样做:

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

        使用 UIKit;是必需的。

        【讨论】:

        • 在 IOS8 UIAlertView Deprecation 之后查看我对 Xamarin 的其他答案更新。
        • “吐司”通常不是模态的。您可以开展业务,因为它不会阻止 UI。但是,UIAlert 视图是模态的。
        • @ScottAhten 同意!你能想出一种方法来制作一个不会挡住视线的可重复使用的吐司吗?
        【解决方案6】:

        准备好复制粘贴的 Swift 3 解决方案:

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

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

        【讨论】:

          【解决方案7】:

          斯威夫特 2.0:

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

          下载 HRToast + UIView.swift 类并拖放到项目中。确保在对话框中选中“如果需要,复制项目”。

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

          【讨论】:

            【解决方案8】:

            如果你真的只想要 android toast 的外观,那么试试这个库,它运行良好,在我的几个应用中使用过

            https://github.com/ecstasy2/toast-notifications-ios 运行良好...

            【讨论】:

            • 尝试发布部分代码 sn-p.link 只有不喜欢的答案
            【解决方案9】:

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

            斯威夫特

            How to Toast message in Swift?

            【讨论】:

              【解决方案10】:

              我知道这个问题已经很老了,但我发现自己在这里想知道同样的事情,我找到了解决方案,所以我想我会分享。此方法允许在您设置的时间延迟后解除警报。

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

              如果您收到导致应用程序崩溃的错误,可能是因为 alertConroller 正在后台线程上运行。要解决这个问题,请将您的代码包装在:

              DispatchQueue.main.async(execute: {
              
              });
              

              当用户单击消息下方的“确定”按钮时,此方法允许关闭消息

              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)
              

              【讨论】:

                【解决方案11】:

                Daniele D 有一个优雅的解决方案,但 UIAlertView 已被弃用。改用 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];
                    });
                

                【讨论】:

                  【解决方案12】:

                  我决定推出一个更完整的 Xamarin.iOS / MonoTouch 解决方案,它对我来说非常有用。

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

                  更新 UIAlertView 在 IOS 8 中已弃用。这里是新方法:

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

                  如果您希望吐司位于屏幕底部而不是中间,请使用

                  UIAlertControllerStyle.ActionSheet
                  

                  如果该方法是从后台线程(不是主 UI 线程)调用的,则需要 BeginInvokeOnMainThread,这意味着只需像这样调用它。

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

                  【讨论】:

                  • 查看我对 Native iOS 的其他答案
                  【解决方案13】:

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

                  【讨论】:

                    【解决方案14】:

                    另一个快速简单的 toast 实现。 单个文件,复制粘贴到您的应用中:

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

                    【讨论】:

                      【解决方案15】:

                      我编写了最简单的代码,它对我来说总是完美无缺。

                      在 Appdelegate.h 中添加这一行

                      -(void) showToastMessage:(NSString *) 消息;

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

                      现在在您想要使用的任何 ViewController 中,只需导入 #import "AppDelegate.h" 并使用以下代码。

                      用于显示 toast 消息

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

                      【讨论】:

                        【解决方案16】:

                        斯威夫特 4+

                        除非您正在寻找某种 UIAlertController 不会提供给您的额外功能,否则您无需下载任何内容。

                        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)
                        

                        上面的代码显示了一个标题为“错误”的警报对话框、描述消息和一个确定按钮,以便用户可以关闭警报。

                        【讨论】:

                          【解决方案17】:

                          这是文档: https://developer.apple.com/documentation/uikit/uialertcontroller

                          这是一个实现类的例子:

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

                          【讨论】:

                            【解决方案18】:

                            对于 Swift UI,我使用这个开源代码:https://github.com/huynguyencong/ToastSwiftUI。它易于使用。

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

                            【讨论】:

                              【解决方案19】:

                              你可以使用,我一直都在使用,这在目标 c 中效果很好。

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

                              此处提供:

                              AviToast Github.

                              【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 2016-05-18
                              • 1970-01-01
                              • 2018-05-18
                              • 2017-07-16
                              • 1970-01-01
                              • 1970-01-01
                              • 2011-04-26
                              相关资源
                              最近更新 更多