runloop实现的同步弹窗

今天介绍使用runloop实现,用return返回点击的结果的方式,首先看一下自定义弹窗的实现代码:

KSPopupView *popup = [[KSPopupView alloc] init];
NSInteger buttonIndex = [popup doModal];
NSLog(@"选择了%ld", (long)buttonIndex);
@implementation KSPopupView {
BOOL _bModel;
NSInteger _selectBtnIndex;
}

  • (NSInteger)doModal {
    [self performSelector:@selector(showAlert)];

    _bModel = YES;
    while (_bModel) {
    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return _selectBtnIndex;
    }

  • (void)showAlert {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 200, 100)];
    [view setBackgroundColor:[UIColor redColor]];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [button setTitle:@"ok" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor greenColor]];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    }

  • (void)buttonClick:(UIButton *)button {
    [button.superview removeFromSuperview];
    _selectBtnIndex = 1;
    _bModel = NO;
    }
    ok,没有问题,假如你想使用系统自带的UIAlertView的话,也是一样的,只是不要在程序刚启动的时候调用,不然会无法弹出(原因暂时还不知道),下面是UIAlertView的例子:

  • (NSInteger)doModal {
    [self showAlert];
    _bModel = YES;
    while (_bModel) {
    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    return _selectBtnIndex;
    }

  • (void)showAlert {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"okookoko" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alertView show];
    }

  • (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    _selectBtnIndex = buttonIndex;
    _bModel = NO;
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容