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

发布于 2024-09-24 08:59:03 字数 185 浏览 8 评论 0原文

我想在 iPhone/iPad 上显示一条临时消息,显示操作的确认,或有关某些后台活动的一些快速状态。

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

建议表示赞赏。

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.

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.

Suggestions appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

梦途 2024-10-01 08:59:03

cocoacontrols.com 上有一个模拟 Android 风格的 Toast 弹出窗口的用户库。可能就是您正在寻找的东西。

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

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

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

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

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

梦回旧景 2024-10-01 08:59:03

创建一个继承自 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]; 
}

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

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

作为一个很好的副作用,当您呈现此视图时,背景会变暗,并且您将获得任何警报视图的漂亮的摆动动画。

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:

- (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.

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.

家住魔仙堡 2024-10-01 08:59:03

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

UIAlertView

编辑:抱歉,没有看看它会自行消失。我认为您需要得到用户对收到的消息的确认。 UIAlertView 几乎做到了这一点。不确定它是否会逐渐消失,除非您使用的应用程序具有基于计时器或基于事件的延迟的视图,该延迟将显示视图,然后最终将其删除。

第二次编辑:找到了实现它的方法。您可以在指定的一段时间后手动调用关闭功能。 (抱歉,帖子很乱)它看起来像这样:

//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];

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

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.

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];
泛滥成性 2024-10-01 08:59:03

使用带有 nil 标题和 nil 按钮的 UIAlertView,然后在需要时将其关闭。我是这样做的:

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

@interface StatusMessageController : UIViewController {
    UIAlertView *statusAlert;
}

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

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

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

您也可以随时通过以下方式关闭警报:

[statusAlert dismissWithClickedButtonIndex:0 animated:YES];

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

statusAlert.message = @"Looking up user";

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

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

@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:

- (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";
纵山崖 2024-10-01 08:59:03

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

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

框架会根据文本长度自动调整。

您可以使用它执行以下操作:[self.view addSubview: [[ToastAlert alloc] initWithText: @"Sent"]];,它将被自动删除,因此不需要引用。

我还没有实现这一点,但您可以创建一个静态方法来缩短和澄清指令,类似于:[ToastAlert showText: @"Sent" inView: self.view];

类:

ToastAlert.h

@interface ToastAlert : UILabel {

}

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

@end

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

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

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.

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.

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];.

The class:

ToastAlert.h

@interface ToastAlert : UILabel {

}

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

@end

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
暮年慕年 2024-10-01 08:59:03

我最终创建了自己的课程。没有继承自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]; }];
}

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

-(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]; }];
}
生来就爱笑 2024-10-01 08:59:03

与 @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
    ];
}

使用它:

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

将其放入 NSObject 的类别或始终保留它的东西中。

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

- (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.

智商已欠费 2024-10-01 08:59:03

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

*Swift 2.2 Answer:

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)
笙痞 2024-10-01 08:59:03

这只是 user2234810 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)

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

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)
小鸟爱天空丶 2024-10-01 08:59:03

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

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

StatusAlertExample 应用程序屏幕显示

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.

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

StatusAlertExample application screenshow

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文