创建模态提醒窗口(UIAlertView)
UIAlertView类创建一个模态提醒窗口,可以包含标题、消息、按钮、文本框,模态UI元素要求用户必须与用户交互以后才可以进行其他事情。
1、创建一个最简单的UIAlertView,UIAlertView初始化代码如下:
显示界面如下:UIAlertView *view=[[UIAlertView alloc] initWithTitle:@"标题" message:@"内容" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil]; view.alertViewStyle=UIAlertViewStyleDefault; view.tag=1; [view show]; [view release];
参数说明:
initWithTitle:显示在顶端的标示 message:显示的内容 delegate:用来相应提醒的对象,一般设置为self,如果不执行任何操作的话,可设置为nil cancelbuttonTitle:视图中默认按钮标题 otherButtonTitls:视图中其他按钮标题,是一个数组,以nil结尾 view.alertViewStyle用来定义提醒视图的外观,有四种选择方案,分别是: UIAlertViewStyleDefault 默认的样式,不包含任何文本框 UIAlertViewStylePlainTextInput 有一个常规文本输入框 UIAlertViewStyleSecureTextInput 一个密码输入框 UIAlertViewStyleLoginAndPasswordInput 一个常规文本框与密码文本框 view.tag 假如程序中有多个UIAlertView时,我们可以使用这个来标识具体是那一个
下面我们来看delegate参数,他指明有哪个类来响应用户的操作或者读取文本框的内容。响应类必须遵守UIAlertViewDelegate协议。
使用的时候首先在头文件(.h)里声明尊送UIAlertViewDelegate协议。声明如下:
这样就完成了声明。然后我们去实现它@interface MyViewController:UIViewController<UIAlertViewDelegate> -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex; -(IBAction)MyUIAlertView; @end
如果要响应用户的操作的话,我们可以实现:-(void)MyUIAlertView{ UIAlertView *view=[[UIAlertView alloc] initWithTitle:@"" message:@"" deleagte:self cancelButtonTitle:@"" otherButtonTitles:@"",nil] view.alertViewStyle=UIAlertViewStyleLoginAndPasswordInput ; view.tag=1; //在这里我们可以通过创建UITextField来关联这个的输入框并设置键盘的相应方式 UITextField *text1=[view textFieldAtIndex:0];//获取文本框对象 UITextField *text2=[view textFieldAtIndex:1]; text1.keyboardType=UIKeyboardTypeNumberPad; text2.keyboardType=UIKeyboardTypeNumbersAndPunctuation [view show]; [view release]; }
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ NSLog(@"title:%@",alertView.title)//获取标题 NSLog(@"message:%@",alert.message)//获取message; //alertView.tag 如果有多个的话,我们可以依据此判断点击了哪个一,返回一个UNInteger类型值 if(buttonIndex==0){//buttonIndex 表示button的索引,从左向右从0开始 //执行一些操作 } [ [alertView textFieldAtIndex:0] text]//如果有文本框的话,可以使用此方法获取文本框的内容 }