iOS多个弹框按顺序依次弹出 比如首页弹窗

之前我也被这种需求所困扰,虽然产品经理很傻逼,但是人家提出的有道理,咱们也只有接受的份。 好了,抱怨归抱怨,代码还有继续码不是。

其实最简单的解决方案就是 GCD 开个线程就ok了

话不说啥,上代码

- (void)viewDidAppear:(BOOL)animated {//这个动作要在首页接口数据全部完成后才可以,不然你数据都不全,上哪去线上一些弹窗之类的呢
    [super viewDidAppear:animated];
    //创建一个队列,串行并行都可以,主要为了操作信号量
    dispatch_queue_t queue = dispatch_queue_create("com.se7en.alert", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        //创建一个初始为0的信号量
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        //第一个弹框,UI的创建和显示,要在主线程(不然你运行的时候回看到警告。如果你看不到,说明你的iOS版本太低,之后会不会直接报错,那要看苹果公司的码农怎么想了)
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert1 = [UIAlertController alertControllerWithTitle:@"第一个弹窗UI" message:@"完美的解决方案吗?" preferredStyle:UIAlertControllerStyleAlert];
            [alert1 addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //点击Alert上的按钮,我们发送一次信号。
                dispatch_semaphore_signal(sema);
            }]];
            [self presentViewController:alert1 animated:YES completion:nil];
        });

        //等待信号触发,注意,这里是在我们创建的队列中等待(当然了DISPATCH_TIME_FOREVER,可以根据自己的需求自行修改)
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        //上面的等待到信号触发之后,再创建第二个Alert
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert2 = [UIAlertController alertControllerWithTitle:@"第二个弹窗UI" message:@"完美的解决方案吗??" preferredStyle:UIAlertControllerStyleAlert];
            [alert2 addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                dispatch_semaphore_signal(sema);
            }]];
            [self presentViewController:alert2 animated:YES completion:nil];
        });

        //同理,创建第三个Alert
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert3 = [UIAlertController alertControllerWithTitle:@"第三个弹窗UI" message:@"完美的解决方案吗???" preferredStyle:UIAlertControllerStyleAlert];
            [alert3 addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                dispatch_semaphore_signal(sema);
            }]];
            [self presentViewController:alert3 animated:YES completion:nil];
        });
    });
}

希望对大家有帮助谢谢


版权声明:本文为weixin_43485231原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。