天天看点

在UIAlterView的代理方法中 点击确定时 添加一个UIView到[[UIApplication sharedApplication].keyWindow上只出现了0.5秒左右就消失的问题

昨天,遇到一个很奇葩的问题,看下面代码:

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self.navigationController popViewControllerAnimated:YES];
            break;
        }
        case 1:
        {
            UIView *v = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
            v.backgroundColor = [UIColor redColor];
            [[UIApplication sharedApplication].keyWindow addSubview:v];
            break;
        }
        default:
            break;
    }
}
           

在弹出一个警告框的时候,我想点击确定按钮,然后加一个view到window上,可是我发现,这个view只出现了零点几秒就消失了。

在我无助的时候,请教了老大,发现原来alertview也是加在window上的,在点击确定的时候,删除alterview的同时,把刚添加的view也跟着删除了。

所以,我就延时一段时间后在生成这个view:

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self.navigationController popViewControllerAnimated:YES];
            break;
        }
        case 1:
        {
            
            [self performSelector:@selector(delayView) withObject:nil afterDelay:0.6];
            break;
        }
        default:
            break;
    }
}

- (void)delayView{
    UIView *v = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    v.backgroundColor = [UIColor redColor];
    [[UIApplication sharedApplication].keyWindow addSubview:v];
}
           

这样view就不会出现消失的情况了,注意延时的时间要大于0.5秒。

继续阅读