警报视图不会消失[iOS]

时间:2014-02-13 07:19:26

标签: ios iphone objective-c

我创建了一个自定义警报视图,其中我创建了自定义按钮并删除了默认按钮。单击自定义按钮时,警报视图不会消失。请帮我解决这个问题。我使用以下代码,

UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[alertView show];
UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(100,25,100,30)];
[alertView addSubview:lbladdblockname];

3 个答案:

答案 0 :(得分:1)

1.包含你的.h文件:UIAlertViewDelegate

2.请遵循以下实施......

UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil]; 
[alertView show];
UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(100,25,100,30)];
[alertView addSubview:lbladdblockname];    
[self performSelector:@selector(dismiss:) withObject:alert1 afterDelay:1.0];

解雇方法将是......

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

或者你想自定义视图而不是使用

 UIAlertView*testAlert=[[UIAlertView alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];


UIButton*testButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[testButton setFrame:CGRectMake(20, 20, 40, 40)];

[testButton setTitle:@"Hello" forState:UIControlStateNormal];
[testButton addTarget:self action:@selector(someAction) forControlEvents:UIControlEventTouchUpInside];
[testAlert addSubview:testButton];
 [testAlert show];

-(void)someAction

{
[testAlert removeFromSuperView];
}

答案 1 :(得分:1)

如果您的类是UIAlertView的子类,那么您可以通过调用此方法来解除它。

[alert dismissWithClickedButtonIndex:0 animated:TRUE];

如果您在课程中使用此方法,则可以使用自我代替警告

答案 2 :(得分:1)

要解决此问题,请执行以下操作:

在标题中定义alertView,然后:

- (void)viewDidLoad 
{
    alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];

    UILabel *lbladdblock=[[UILabel alloc] initWithFrame:CGRectMake(0,0,20,30)];
    [lbladdblock setText:@"custom Message"];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTitle:@"Dismiss!" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(dismissMe) forControlEvents:UIControlEventTouchUpInside];

    [alertView addSubview:lbladdblock];
    [alertView addSubview:btn];

    [alertView show];
}

 -(void)dismissMe
{
    [alertview dismissWithClickedButtonIndex:0 animated:YES];
}

此外,在ios7中无法使用AFAIK addSubViewalertView,因此您的代码仅适用于以前的版本。请参阅此thread

由于您没有使用UIAlertView的内置功能(在所有参数中传递nil)您应该更喜欢一些自定义警报视图。请参阅链接中的示例警报视图。

希望它有所帮助!