我們知道UIAlertView使用delegate返回數據實現的枕扫,使用麻煩脐雪,之前介紹過用Block實現的例子《ios實戰(zhàn)-使用Block的UIAlertView》
今天介紹使用runloop實現惨好,用return返回點擊的結果的方式盒音,首先看一下自定義彈窗的實現代碼:
KSPopupView *popup = [[KSPopupView alloc] init];
NSIntegerbuttonIndex = [popup doModal];
NSLog(@"選擇了%ld", (long)buttonIndex);
@implementationKSPopupView{BOOL_bModel;NSInteger_selectBtnIndex;
}
-?(NSInteger)doModal?{
[selfperformSelector:@selector(showAlert)];
_bModel?=YES;while(_bModel)?{
[[NSRunLoopmainRunLoop]?runMode:NSDefaultRunLoopModebeforeDate:[NSDatedistantFuture]];
}return_selectBtnIndex;
}
-?(void)showAlert?{UIView*view?=?[[UIViewalloc]?initWithFrame:CGRectMake(20,100,200,100)];
[view?setBackgroundColor:[UIColorredColor]];UIButton*button?=?[[UIButtonalloc]?initWithFrame:CGRectMake(0,0,50,30)];
[button?setTitle:@"ok"forState:UIControlStateNormal];
[button?setBackgroundColor:[UIColorgreenColor]];
[button?addTarget:selfaction:@selector(buttonClick:)?forControlEvents:UIControlEventTouchUpInside];
[view?addSubview:button];
[[UIApplicationsharedApplication].keyWindow?addSubview:view];
}
-?(void)buttonClick:(UIButton*)button?{
[button.superview?removeFromSuperview];
_selectBtnIndex?=1;
_bModel?=NO;
}
ok,沒有問題蝌诡,假如你想使用系統自帶的UIAlertView的話挎春,也是一樣的看疙,只是不要在程序剛啟動的時候調用,不然會無法彈出(原因暫時還不知道),下面是UIAlertView的例子:
- (NSInteger)doModal {
[selfshowAlert];
_bModel?=YES;while(_bModel)?{
[[NSRunLoopmainRunLoop]?runMode:NSDefaultRunLoopModebeforeDate:[NSDatedistantFuture]];
}return_selectBtnIndex;
}
-?(void)showAlert?{UIAlertView*alertView?=?[[UIAlertViewalloc]?initWithTitle:@""message:@"okookoko"delegate:selfcancelButtonTitle:@"cancel"otherButtonTitles:@"ok",nil];
[alertView?show];
}
-?(void)alertView:(UIAlertView*)alertView?clickedButtonAtIndex:(NSInteger)buttonIndex?{
_selectBtnIndex?=?buttonIndex;
_bModel?=NO;
}