iOS 中的 Android Toast 等效项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/24893788/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Toast equivalent in iOS
提问by Bil Kimes
Does anyone know what the Java Toastequivalent 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.
有谁知道这个 iOS Objective C 事件的Java Toast等价物在 Fragment 中是什么?下面是我在 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];
    }
}
回答by Lucia Belardinelli
I found this amazing class in github that works like a charm. Toast for iOSIt is enough to import the UIView+Toast.h and UIView+Toast.m files and then add
我在 github 中发现了这个神奇的类,它的作用就像一个魅力。 Toast for iOS只需导入 UIView+Toast.h 和 UIView+Toast.m 文件,然后添加
[self.view makeToast:@"This is a piece of toast."];
as written in the page examples.
如页面示例中所述。
回答by Vivo
There is no android toast equivalent in iOS.
在 iOS 中没有 android toast 等价物。
But there are always workarounds like
但总有一些解决方法,比如
you can animate a view and play with its alpha
您可以为视图设置动画并使用其 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
如果你不想在 3 秒内慢慢淡出,你可以使用
[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
并将动画持续时间减少到 0.5f 左右。我认为使用较短的淡出时间比简单地将隐藏设置为 YES 感觉更好
回答by wboland
I handled it with a simple static UI Helper method using the Key Window:
我使用 Key Window 通过一个简单的静态 UI Helper 方法处理它:
+(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];
                     }
         ];
    }];
}
回答by earnshavian
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:
我们已经在我们的开源库Raisin Toast 中实现了类似的功能。将文件添加到项目后,设置非常简单:
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.
该实现使用了第二个 UIWindow,并且由于 RZErrorMessenger 类方法,它在任何地方都可用。
回答by Daniele D.
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];
});
UPDATEUIAlertView is deprecated in IOS 8. Here the new way:
更新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];
});
EDIT:For the ones that using Xamarin.IOS you can do like this:
编辑:对于那些使用 Xamarin.IOS 你可以这样做:
new UIAlertView(null, message, null, "OK", null).Show();
using UIKit; is required.
使用 UIKit;是必须的。
回答by Tim Autin
A Swift 3 solution ready for copy paste:
准备复制粘贴的 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();
        }
    }
}
The UIPaddingLabel class:
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;
        }
    }
}
回答by A.G
Swift 2.0:
斯威夫特 2.0:
Use https://github.com/Rannie/Toast-Swift/blob/master/SwiftToastDemo/Toast/HRToast%2BUIView.swift.
使用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.
下载 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")
回答by Yogesh Lolusare
Objective C
目标 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
迅速
回答by Tyler Pashigian
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:
如果您收到导致应用程序崩溃的错误,可能是因为 alertConroller 正在后台线程上运行。要解决此问题,请将您的代码包装在:
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)
回答by TomV
Daniele D has an elegant solution, but UIAlertView is deprecated. Use UIAlertController instead:
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];
    });

