【转】iPhone 模态对话框 立即返回结果
原文:http://blog.csdn.net/xianpengliu/article/details/6591624
iPhone中的UIAlertView用于显示一个模态对话框
显示时设置代理delegate,当用户点击对话框中按钮时,系统将会调用delegate的函数
从而使得程序可以根据用户的选择进行相应的处理
这里使用了代理模式,虽然代理模式在ios的设计中有很多优雅的地方
但是这里,用在返回模态对话框的结果,未免有点儿不合时宜
每次用到这个,我就非常怀念MFC中的模态对话框:
- ReturnValue ret = dlg.doModal();
- if (ret == x) {
- ...
- } else {
- ...
- }
下面,封装一个类来实现这种简介的操作(代码摘自《iPhone开发秘籍》):
- #import <UIKit/UIKit.h>
- @interface ModalAlert : NSObject
- + (BOOL) ask: (NSString *) question;
- + (BOOL) confirm:(NSString *) statement;
- @end
- #import "ModalAlert.h"
- @interface ModalAlertDelegate : NSObject <UIAlertViewDelegate>
- {
- CFRunLoopRef currentLoop;
- NSUInteger index;
- }
- @property (readonly) NSUInteger index;
- @end
- @implementation ModalAlertDelegate
- @synthesize index;
- // Initialize with the supplied run loop
- -(id) initWithRunLoop: (CFRunLoopRef)runLoop
- {
- if (self = [super init]) currentLoop = runLoop;
- return self;
- }
- // User pressed button. Retrieve results
- -(void) alertView: (UIAlertView*)aView clickedButtonAtIndex: (NSInteger)anIndex
- {
- index = anIndex;
- CFRunLoopStop(currentLoop);
- }
- @end
- @implementation ModalAlert
- +(NSUInteger) queryWith: (NSString *)question button1: (NSString *)button1 button2: (NSString *)button2
- {
- CFRunLoopRef currentLoop = CFRunLoopGetCurrent();
- // Create Alert
- ModalAlertDelegate *madelegate = [[ModalAlertDelegate alloc] initWithRunLoop:currentLoop];
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:question message:nil delegate:madelegate cancelButtonTitle:button1 otherButtonTitles:button2, nil];
- [alertView show];
- // Wait for response
- CFRunLoopRun();
- // Retrieve answer
- NSUInteger answer = madelegate.index;
- [alertView release];
- [madelegate release];
- return answer;
- }
- + (BOOL) ask: (NSString *) question
- {
- return [ModalAlert queryWith:question button1: @"No" button2: @"Yes"];
- }
- + (BOOL) confirm: (NSString *) statement
- {
- return [ModalAlert queryWith:statement button1: @"Cancel" button2: @"OK"];
- }
- @end
- NSUInteger answer = [ModalAlert ask:@"Are you sure?"];