ios实战-runloop实现的同步弹窗

我们知道UIAlertView使用delegate返回数据实现的,使用麻烦,之前介绍过用Block实现的例子ios实战-使用Block的UIAlertView

今天介绍使用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;
}


转载于:https://my.oschina.net/iq19900204/blog/411718

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值