如何在iPhone / iPad / iOS上显示临时弹出消息

时间:2023-01-28 22:30:18

I'd like to display a temporary message on the iPhone/iPad displaying confirmation of an action, or some quick status about some background activity.

我想在iPhone / iPad上显示一条临时消息,显示动作确认,或者某些背景活动的快速状态。

Is there a standard control to do this? I've seen apps do this. A rounded rectangle, dark and partially transparent with text inside. It does not ask for user input but disappears on its own in some short period of time. Android has a similar construct which is standard. Also similar to the windows displayed by Growl.

有没有标准控制来做到这一点?我见过应用程序这样做。圆角矩形,深色和部分透明,内有文字。它不会要求用户输入,而是在很短的时间内自行消失。 Android有一个类似的标准构造。也类似于Growl显示的窗口。

Suggestions appreciated.

建议表示赞赏。

10 个解决方案

#1


15  

There is a user library on cocoacontrols.com that emulates the Android-style Toast pop-ups. Might be what you are looking for.

cocoacontrols.com上有一个用户库,可以模拟Android风格的Toast弹出窗口。可能就是你要找的东西。

http://www.cocoacontrols.com/platforms/ios/controls/altoastview

http://www.cocoacontrols.com/platforms/ios/controls/altoastview

There's also this one that follows the same idea.

还有一个遵循相同想法的那个。

http://www.cocoacontrols.com/platforms/ios/controls/itoast

http://www.cocoacontrols.com/platforms/ios/controls/itoast

#2


15  

Create a class that inherits from UIAlertView. In your constructor just call [super init] and then add any view you want as a subview. You can even design this view in Interface Builder. Something like this:

创建一个继承自UIAlertView的类。在构造函数中,只需调用[super init],然后将所需的任何视图添加为子视图。您甚至可以在Interface Builder中设计此视图。像这样的东西:

- (id)initWithMessage:(NSString *)message dismissAfter:(NSTimeInterval)interval
{
  if ((self = [super init]))
  {
     CustomView * customView = [[[CustomView alloc] init] autorelease]; // or load from NIB
     [self addSubview:customView];
     [self performSelector:@selector(dismissAfterDelay) withObject:nil afterDelay:interval];
  }
  return self;
}

- (void)dismissAfterDelay
{
  [self dismissWithClickedButtonIndex:0 animated:YES]; 
}

To display your custom alert view just init it, and call show as with a regular UIAlertView.

要显示自定义警报视图,只需初始化它,并像使用常规UIAlertView一样调用show。

CustomAlertView * cav = [[CustomAlertView alloc] initWithMessage:@"Doing Something];
[cav show];
[cav release];

As an nice side-effect, when you present this view the background will darken and you will get the nice wobbly animation for any alert view.

作为一个很好的副作用,当你呈现这个视图时,背景会变暗,你会得到任何警报视图的漂亮摇晃动画。

#3


9  

Use UIAlertView. Here's a quick link to a simple example:

使用UIAlertView。这是一个简单示例的快速链接:

UIAlertView

UIAlertView中

Edited: Sorry, didn't see about disappearing on it's own. I think you need to have some confirmation by users of messages received. UIAlertView pretty much accomplishes that. Not sure if you have it gradually fade away unless you're in an app with a view that has a timer or event based delay that will show a view and then eventually remove it.

编辑:对不起,没看到它自己消失了。我认为您需要对用户收到的消息进行一些确认。 UIAlertView几乎完成了这一点。不确定你是否逐渐消失,除非你在一个具有定时器或基于事件的延迟视图的应用程序中显示视图,然后最终将其删除。

Second edit: Found a way to implement it. You can manually call the dismiss function after some set time that you've designated. (Sorry for the messy post) It would look something like this:

第二次编辑:找到实现它的方法。您可以在指定的某个设定时间后手动调用解除功能。 (抱歉凌乱的帖子)它看起来像这样:

//Create UIAlertView alert
alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Some message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil];

//After some time
[alert dismissWithClickedButtonIndex:0 animated:TRUE];

#4


8  

Use a UIAlertView with nil title and nil buttons, then dismiss it when desired. Here's how I did this:

使用带有nil title和nil按钮的UIAlertView,然后在需要时将其关闭。这是我如何做到这一点:

Create an instance variable for the alert view in your .h file:

在.h文件中为警报视图创建实例变量:

@interface StatusMessageController : UIViewController {
    UIAlertView *statusAlert;
}

In your .m file, create a method to show the alert view and start a timer, and another to handle when the timer expires to dismiss the alert:

在.m文件中,创建一个方法来显示警报视图并启动一个计时器,另一个方法来处理计时器到期以解除警报:

- (void)showStatus:(NSString *)message timeout:(double)timeout {
    statusAlert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:nil];
    [statusAlert show];
    [NSTimer scheduledTimerWithTimeInterval:timeout
                                     target:self
                                   selector:@selector(timerExpired:)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)timerExpired:(NSTimer *)timer {
    [statusAlert dismissWithClickedButtonIndex:0 animated:YES];
}

Whenever you want to show the status message, invoke it:

每当您想要显示状态消息时,请调用它:

[self showStatus:@"Computing" timeout:4.5];

At any time, you can also dismiss the alert with:

您可以随时通过以下方式解除警报:

[statusAlert dismissWithClickedButtonIndex:0 animated:YES];

You can also change the message on-the-fly with new status:

您还可以使用新状态即时更改消息:

statusAlert.message = @"Looking up user";

#5


8  

I created an Android-Kind toast, pretty simple because I don't need more functionality in it for now.

我创建了一个Android-Kind Toast,非常简单,因为我现在不需要更多的功能。

When it is shown it is added at the bottom of the parent's view, so if that view is the VC's view then it will be at the bottom center of the device.

当显示它时,它被添加到父视图的底部,所以如果该视图是VC的视图,那么它将位于设备的底部中心。

The frame is autoadjusted to the text length.

框架自动调整为文本长度。

You use it doing: [self.view addSubview: [[ToastAlert alloc] initWithText: @"Sent"]];, it will be auto-removed so no reference is needed.

你使用它做:[self.view addSubview:[[ToastAlert alloc] initWithText:@“Sent”]];,它将被自动删除,因此不需要引用。

I haven't implemented this, but you can create a static method to shorten and clarify the instruction, sort of: [ToastAlert showText: @"Sent" inView: self.view];.

我没有实现这个,但你可以创建一个静态方法来缩短和澄清指令,排序:[ToastAlert showText:@“Sent”inView:self.view] ;.

The class:

班上:

ToastAlert.h

ToastAlert.h

@interface ToastAlert : UILabel {

}

- (id)initWithText: (NSString*) msg;

@end

ToastAlert.m

ToastAlert.m

#import "ToastAlert.h"
#import <QuartzCore/QuartzCore.h>

@implementation ToastAlert

#define POPUP_DELAY  1.5

- (id)initWithText: (NSString*) msg
{

    self = [super init];
    if (self) {

        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        self.textColor = [UIColor colorWithWhite:1 alpha: 0.95];
        self.font = [UIFont fontWithName: @"Helvetica-Bold" size: 13];
        self.text = msg;
        self.numberOfLines = 0;
        self.textAlignment = UITextAlignmentCenter;
        self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;


    }
    return self;
}

- (void)didMoveToSuperview {

    UIView* parent = self.superview;

    if(parent) {

        CGSize maximumLabelSize = CGSizeMake(300, 200);
        CGSize expectedLabelSize = [self.text sizeWithFont: self.font  constrainedToSize:maximumLabelSize lineBreakMode: NSLineBreakByTruncatingTail];

        expectedLabelSize = CGSizeMake(expectedLabelSize.width + 20, expectedLabelSize.height + 10);

        self.frame = CGRectMake(parent.center.x - expectedLabelSize.width/2,
                                parent.bounds.size.height-expectedLabelSize.height - 10,
                                expectedLabelSize.width,
                                expectedLabelSize.height);

        CALayer *layer = self.layer;
        layer.cornerRadius = 4.0f;

        [self performSelector:@selector(dismiss:) withObject:nil afterDelay:POPUP_DELAY];
    }
}

- (void)dismiss:(id)sender {
    // Fade out the message and destroy self
    [UIView animateWithDuration:0.6  delay:0 options: UIViewAnimationOptionAllowUserInteraction
                     animations:^  { self.alpha = 0; }
                     completion:^ (BOOL finished) { [self removeFromSuperview]; }];
}

@end

#6


4  

I ended up creating my own class. Didn't inherit from UIAlertView. General structure is,

我最终创建了自己的课程。没有从UIAlertView继承。一般结构是,

-(id)initWithText:(NSString *)msg {
    // Create a view. Put a label, set the msg
    CALayer *layer = self.layer;
    layer.cornerRadius = 8.0f;
    ...
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [self performSelector:@selector(dismiss:) withObject:nil afterDelay:2.0];
    [self setAutoresizesSubviews:FALSE];
    return self;
}


- (void)dismiss:(id)sender {
    // Fade out the message and destroy self
    [UIView animateWithDuration:0.5 
                 animations:^  { self.alpha = 0; }
                 completion:^ (BOOL finished) { [self removeFromSuperview]; }];
}

#7


2  

Similar answer to @marco-mustapic's, but without inheritance.

类似于@ marco-mustapic的答案,但没有继承。

- (void)dismissAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)showPopupWithTitle:(NSString *)title
                    mesage:(NSString *)message
              dismissAfter:(NSTimeInterval)interval
{
    UIAlertView *alertView = [[UIAlertView alloc]
           initWithTitle:title
                 message:message
                delegate:nil
        cancelButtonTitle:nil
        otherButtonTitles:nil
    ];
    [alertView show];
    [self performSelector:@selector(dismissAlert:)
               withObject:alertView
               afterDelay:interval
    ];
}

To use it:

要使用它:

[self showPopupWithTitle:@"Hi" message:@"I like pie" dismissAfter:2.0];

Throw it into a category on NSObject or something to always have it around.

把它扔到NSObject上的一个类别或总是有它的东西。

#8


2  

*Swift 2.2 Answer:

* Swift 2.2答案:

func showPopupWithTitle(title: String, message: String, interval: NSTimeInterval) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    presentViewController(alertController, animated: true, completion: nil)
    self.performSelector(#selector(dismissAlertViewController), withObject: alertController, afterDelay: interval)
}

func dismissAlertViewController(alertController: UIAlertController) {
    alertController.dismissViewControllerAnimated(true, completion: nil)
}

showPopupWithTitle("Title", message: "Message", interval: 0.5)

#9


2  

This is just a Swift 3 version of user2234810 2.2 version.

这只是用户2234810 2.2版本的Swift 3版本。

func showPopupWithTitle(title: String, message: String, interval: TimeInterval) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    present(alertController, animated: true, completion: nil)
    self.perform(#selector(dismissAlertViewController), with: alertController, afterDelay: interval)
}

func dismissAlertViewController(alertController: UIAlertController) {
    alertController.dismiss(animated: true, completion: nil)
}
showPopupWithTitle(title: "Title", message: "Message", interval: 0.5)

#10


1  

You can use my own StatusAlert framework written in Swift. It gives you ability to show Apple system-like alert as well as present the same alert without an image, title or message anywhere in UIView.

您可以使用我自己的用Swift编写的StatusAlert框架。它使您能够显示类似Apple系统的警报,并在UIView中的任何位置显示相同的警报,而无需图像,标题或消息。

It is available via Cocoapods and Carthage and supports iPhone X, Safe Areas layout, iPads and allows some customizations.

它可以通过Cocoapods和Carthage获得,并支持iPhone X,安全区域布局,iPad并允许一些自定义。

如何在iPhone / iPad / iOS上显示临时弹出消息

#1


15  

There is a user library on cocoacontrols.com that emulates the Android-style Toast pop-ups. Might be what you are looking for.

cocoacontrols.com上有一个用户库,可以模拟Android风格的Toast弹出窗口。可能就是你要找的东西。

http://www.cocoacontrols.com/platforms/ios/controls/altoastview

http://www.cocoacontrols.com/platforms/ios/controls/altoastview

There's also this one that follows the same idea.

还有一个遵循相同想法的那个。

http://www.cocoacontrols.com/platforms/ios/controls/itoast

http://www.cocoacontrols.com/platforms/ios/controls/itoast

#2


15  

Create a class that inherits from UIAlertView. In your constructor just call [super init] and then add any view you want as a subview. You can even design this view in Interface Builder. Something like this:

创建一个继承自UIAlertView的类。在构造函数中,只需调用[super init],然后将所需的任何视图添加为子视图。您甚至可以在Interface Builder中设计此视图。像这样的东西:

- (id)initWithMessage:(NSString *)message dismissAfter:(NSTimeInterval)interval
{
  if ((self = [super init]))
  {
     CustomView * customView = [[[CustomView alloc] init] autorelease]; // or load from NIB
     [self addSubview:customView];
     [self performSelector:@selector(dismissAfterDelay) withObject:nil afterDelay:interval];
  }
  return self;
}

- (void)dismissAfterDelay
{
  [self dismissWithClickedButtonIndex:0 animated:YES]; 
}

To display your custom alert view just init it, and call show as with a regular UIAlertView.

要显示自定义警报视图,只需初始化它,并像使用常规UIAlertView一样调用show。

CustomAlertView * cav = [[CustomAlertView alloc] initWithMessage:@"Doing Something];
[cav show];
[cav release];

As an nice side-effect, when you present this view the background will darken and you will get the nice wobbly animation for any alert view.

作为一个很好的副作用,当你呈现这个视图时,背景会变暗,你会得到任何警报视图的漂亮摇晃动画。

#3


9  

Use UIAlertView. Here's a quick link to a simple example:

使用UIAlertView。这是一个简单示例的快速链接:

UIAlertView

UIAlertView中

Edited: Sorry, didn't see about disappearing on it's own. I think you need to have some confirmation by users of messages received. UIAlertView pretty much accomplishes that. Not sure if you have it gradually fade away unless you're in an app with a view that has a timer or event based delay that will show a view and then eventually remove it.

编辑:对不起,没看到它自己消失了。我认为您需要对用户收到的消息进行一些确认。 UIAlertView几乎完成了这一点。不确定你是否逐渐消失,除非你在一个具有定时器或基于事件的延迟视图的应用程序中显示视图,然后最终将其删除。

Second edit: Found a way to implement it. You can manually call the dismiss function after some set time that you've designated. (Sorry for the messy post) It would look something like this:

第二次编辑:找到实现它的方法。您可以在指定的某个设定时间后手动调用解除功能。 (抱歉凌乱的帖子)它看起来像这样:

//Create UIAlertView alert
alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Some message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil];

//After some time
[alert dismissWithClickedButtonIndex:0 animated:TRUE];

#4


8  

Use a UIAlertView with nil title and nil buttons, then dismiss it when desired. Here's how I did this:

使用带有nil title和nil按钮的UIAlertView,然后在需要时将其关闭。这是我如何做到这一点:

Create an instance variable for the alert view in your .h file:

在.h文件中为警报视图创建实例变量:

@interface StatusMessageController : UIViewController {
    UIAlertView *statusAlert;
}

In your .m file, create a method to show the alert view and start a timer, and another to handle when the timer expires to dismiss the alert:

在.m文件中,创建一个方法来显示警报视图并启动一个计时器,另一个方法来处理计时器到期以解除警报:

- (void)showStatus:(NSString *)message timeout:(double)timeout {
    statusAlert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:nil];
    [statusAlert show];
    [NSTimer scheduledTimerWithTimeInterval:timeout
                                     target:self
                                   selector:@selector(timerExpired:)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)timerExpired:(NSTimer *)timer {
    [statusAlert dismissWithClickedButtonIndex:0 animated:YES];
}

Whenever you want to show the status message, invoke it:

每当您想要显示状态消息时,请调用它:

[self showStatus:@"Computing" timeout:4.5];

At any time, you can also dismiss the alert with:

您可以随时通过以下方式解除警报:

[statusAlert dismissWithClickedButtonIndex:0 animated:YES];

You can also change the message on-the-fly with new status:

您还可以使用新状态即时更改消息:

statusAlert.message = @"Looking up user";

#5


8  

I created an Android-Kind toast, pretty simple because I don't need more functionality in it for now.

我创建了一个Android-Kind Toast,非常简单,因为我现在不需要更多的功能。

When it is shown it is added at the bottom of the parent's view, so if that view is the VC's view then it will be at the bottom center of the device.

当显示它时,它被添加到父视图的底部,所以如果该视图是VC的视图,那么它将位于设备的底部中心。

The frame is autoadjusted to the text length.

框架自动调整为文本长度。

You use it doing: [self.view addSubview: [[ToastAlert alloc] initWithText: @"Sent"]];, it will be auto-removed so no reference is needed.

你使用它做:[self.view addSubview:[[ToastAlert alloc] initWithText:@“Sent”]];,它将被自动删除,因此不需要引用。

I haven't implemented this, but you can create a static method to shorten and clarify the instruction, sort of: [ToastAlert showText: @"Sent" inView: self.view];.

我没有实现这个,但你可以创建一个静态方法来缩短和澄清指令,排序:[ToastAlert showText:@“Sent”inView:self.view] ;.

The class:

班上:

ToastAlert.h

ToastAlert.h

@interface ToastAlert : UILabel {

}

- (id)initWithText: (NSString*) msg;

@end

ToastAlert.m

ToastAlert.m

#import "ToastAlert.h"
#import <QuartzCore/QuartzCore.h>

@implementation ToastAlert

#define POPUP_DELAY  1.5

- (id)initWithText: (NSString*) msg
{

    self = [super init];
    if (self) {

        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        self.textColor = [UIColor colorWithWhite:1 alpha: 0.95];
        self.font = [UIFont fontWithName: @"Helvetica-Bold" size: 13];
        self.text = msg;
        self.numberOfLines = 0;
        self.textAlignment = UITextAlignmentCenter;
        self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;


    }
    return self;
}

- (void)didMoveToSuperview {

    UIView* parent = self.superview;

    if(parent) {

        CGSize maximumLabelSize = CGSizeMake(300, 200);
        CGSize expectedLabelSize = [self.text sizeWithFont: self.font  constrainedToSize:maximumLabelSize lineBreakMode: NSLineBreakByTruncatingTail];

        expectedLabelSize = CGSizeMake(expectedLabelSize.width + 20, expectedLabelSize.height + 10);

        self.frame = CGRectMake(parent.center.x - expectedLabelSize.width/2,
                                parent.bounds.size.height-expectedLabelSize.height - 10,
                                expectedLabelSize.width,
                                expectedLabelSize.height);

        CALayer *layer = self.layer;
        layer.cornerRadius = 4.0f;

        [self performSelector:@selector(dismiss:) withObject:nil afterDelay:POPUP_DELAY];
    }
}

- (void)dismiss:(id)sender {
    // Fade out the message and destroy self
    [UIView animateWithDuration:0.6  delay:0 options: UIViewAnimationOptionAllowUserInteraction
                     animations:^  { self.alpha = 0; }
                     completion:^ (BOOL finished) { [self removeFromSuperview]; }];
}

@end

#6


4  

I ended up creating my own class. Didn't inherit from UIAlertView. General structure is,

我最终创建了自己的课程。没有从UIAlertView继承。一般结构是,

-(id)initWithText:(NSString *)msg {
    // Create a view. Put a label, set the msg
    CALayer *layer = self.layer;
    layer.cornerRadius = 8.0f;
    ...
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [self performSelector:@selector(dismiss:) withObject:nil afterDelay:2.0];
    [self setAutoresizesSubviews:FALSE];
    return self;
}


- (void)dismiss:(id)sender {
    // Fade out the message and destroy self
    [UIView animateWithDuration:0.5 
                 animations:^  { self.alpha = 0; }
                 completion:^ (BOOL finished) { [self removeFromSuperview]; }];
}

#7


2  

Similar answer to @marco-mustapic's, but without inheritance.

类似于@ marco-mustapic的答案,但没有继承。

- (void)dismissAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)showPopupWithTitle:(NSString *)title
                    mesage:(NSString *)message
              dismissAfter:(NSTimeInterval)interval
{
    UIAlertView *alertView = [[UIAlertView alloc]
           initWithTitle:title
                 message:message
                delegate:nil
        cancelButtonTitle:nil
        otherButtonTitles:nil
    ];
    [alertView show];
    [self performSelector:@selector(dismissAlert:)
               withObject:alertView
               afterDelay:interval
    ];
}

To use it:

要使用它:

[self showPopupWithTitle:@"Hi" message:@"I like pie" dismissAfter:2.0];

Throw it into a category on NSObject or something to always have it around.

把它扔到NSObject上的一个类别或总是有它的东西。

#8


2  

*Swift 2.2 Answer:

* Swift 2.2答案:

func showPopupWithTitle(title: String, message: String, interval: NSTimeInterval) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    presentViewController(alertController, animated: true, completion: nil)
    self.performSelector(#selector(dismissAlertViewController), withObject: alertController, afterDelay: interval)
}

func dismissAlertViewController(alertController: UIAlertController) {
    alertController.dismissViewControllerAnimated(true, completion: nil)
}

showPopupWithTitle("Title", message: "Message", interval: 0.5)

#9


2  

This is just a Swift 3 version of user2234810 2.2 version.

这只是用户2234810 2.2版本的Swift 3版本。

func showPopupWithTitle(title: String, message: String, interval: TimeInterval) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    present(alertController, animated: true, completion: nil)
    self.perform(#selector(dismissAlertViewController), with: alertController, afterDelay: interval)
}

func dismissAlertViewController(alertController: UIAlertController) {
    alertController.dismiss(animated: true, completion: nil)
}
showPopupWithTitle(title: "Title", message: "Message", interval: 0.5)

#10


1  

You can use my own StatusAlert framework written in Swift. It gives you ability to show Apple system-like alert as well as present the same alert without an image, title or message anywhere in UIView.

您可以使用我自己的用Swift编写的StatusAlert框架。它使您能够显示类似Apple系统的警报,并在UIView中的任何位置显示相同的警报,而无需图像,标题或消息。

It is available via Cocoapods and Carthage and supports iPhone X, Safe Areas layout, iPads and allows some customizations.

它可以通过Cocoapods和Carthage获得,并支持iPhone X,安全区域布局,iPad并允许一些自定义。

如何在iPhone / iPad / iOS上显示临时弹出消息