iOS常用的对话框就是UIAlertView了,最简单的用法及时Tip提示,并点击按钮关闭对话框。
当然也有需要点击按钮后捕捉事件作其他处理的需求,这就是此片博客出现的原因咯。
1.添加头文件声明:
@interface ViewController : UIViewController<UIAlertViewDelegate>
@property (nonatomic, strong)NSString *urlOpen;
@end
2.添加实现,用NSDictionary来传递所需参数,特殊参数采用property存储:
- (void)viewDidLoad:(NSDictionary *)dict
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib
//初始化AlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AlertViewTest"
message:@"message"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定",nil];
//设置标题与信息,通常在使用frame初始化AlertView时使用
NSString *title=[dict objectForKey:@"title"];
NSString *content=[dict objectForKey:@"content"];
self.urlOpen = [dict objectForKey:@"url"];
alert.title = title;
alert.message = content;
//这个属性继承自UIView,当一个视图中有多个AlertView时,可以用这个属性来区分
alert.tag = 0;
//显示AlertView
[alert show];
[alert release];
}
#pragma marks -- UIAlertViewDelegate --
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
NSLog(@"点击了确定按钮");
@try
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.urlOpen]];
}
@catch (NSException * e) {
return;
}
}
else {
NSLog(@"点击了取消按钮");
}
}
3.因为上面UIAlertView是对象方法,所以在创建时需要这样调用:
+(void)openDialog:(NSDictionary *)dict
{
@try
{
[[ViewController alloc] viewDidLoad:dict];
}
@catch (NSException * e) {
return;
}
}
4.这样就可以通过3的单例方法去随时调用,博主这样的需求,基于cocos2d-x引擎需要。
5.追加其他UIAlertView监听方法
//AlertView已经消失时执行的事件
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"didDismissWithButtonIndex");
}
//ALertView即将消失时的事件
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"willDismissWithButtonIndex");
}
//AlertView的取消按钮的事件
-(void)alertViewCancel:(UIAlertView *)alertView
{
NSLog(@"alertViewCancel");
}
//AlertView已经显示时的事件
-(void)didPresentAlertView:(UIAlertView *)alertView
{
NSLog(@"didPresentAlertView");
}
//AlertView即将显示时
-(void)willPresentAlertView:(UIAlertView *)alertView
{
NSLog(@"willPresentAlertView");
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}