iPhone 模态对话框 立即返回结果

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?"];


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值