27

UIAlertviewDelegate 协议有几个可选方法,包括:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

这似乎表明并非所有按钮单击实际上都会关闭警报视图。但是,我看不到将警报视图配置为不会在按下任何按钮时自动关闭的方法。

我必须创建一个子类来完成这个吗?

为什么 UIAlertViewDelegate 协议有:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex;
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

如果它不支持在每次单击按钮时不关闭警报视图?

顺便说一句:我意识到 UIAlertView 的设计目的。但我的目的是允许用户在应用程序退出之前将一些文本复制到粘贴板上(当警报视图被关闭时会自动发生。

4

5 回答 5

28

是的。子类化UIAlertView然后重载-dismissWithClickedButtonIndex:animated:,例如

@implementation MyAlertView 
-(void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated {
   if (buttonIndex should not dismiss the alert)
      return;
   [super dismissWithClickedButtonIndex:buttonIndex animated:animated];
}
@end

非正式地你可以定义一个

-(void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(id)button;

委托的方法将使其绕过-dismissWithClickedButtonIndex:animated:,但它是无证的,所以我不知道它是否适合你。

于 2010-01-12T20:06:53.887 回答
3

willPresentAlertView:didPresentAlertView:alertView:willDismissWithButtonIndex:alertView:didDismissWithButtonIndex:用于跟踪 UIAlertView 动画的开始和结束。

不需要跟踪 UIAlertView 动画的应用程序可以简单地使用alertView:clickedButtonAtIndex:. 该方法的文档说“调用此方法后接收器会自动关闭”。

于 2010-01-12T20:39:33.223 回答
3

在我看来:没有理由保留 alertView。即使您想保留它,只需考虑通过保留参考来“重新显示”它,然后调用 [alertView show] ==> NO NEED TO SUBCLASS ANYTHING。好消息,嗯?

于 2015-08-11T03:55:11.850 回答
1

警告

从一些消息来源中,我听说很少有应用程序在此过程后被拒绝。在 iOS6 期间我很幸运,所以我在这里展示代码。使用风险自负:-/

子类化是最好的方法。为警报创建一个bool标志是否应该保留。

这是的子类UIAlertView

//
//  UICustomAlertView.h
//

#import <UIKit/UIKit.h>

@interface UICustomAlertView : UIAlertView
{
    
}
@property(nonatomic, assign) BOOL dontDisppear;
@end

//
//  UICustomAlertView.m
//

#import "UICustomAlertView.h"

@implementation UICustomAlertView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated {

    if(self.dontDisppear)
        return;
    [super dismissWithClickedButtonIndex:buttonIndex animated:animated];
}
@end

这就是我在代码中使用它的方式

if(![txtUsername.text isEqualToString:@"admin"] && ![txtPassword.text isEqualToString:@"admin"])
{
     alertLogin.dontDisppear = YES;
     alertLogin.message = NSLocalizedString(@"my_alert", nil);
}
else
{
     alertLogin.dontDisppear = NO;
     // proceed
}
于 2013-04-10T13:09:40.917 回答
1
#import "MLAlertView.h"

@implementation MLAlertView


-(void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated {
}

-(void)dismissNow:(NSInteger)buttonIndex  {
     [super dismissWithClickedButtonIndex:buttonIndex animated:YES];
}
于 2014-12-12T06:53:28.753 回答