UIAlertView使用详解
Ios中为我们提供了一个用来弹出提示框的类 UIAlertView,他类似于javascript中的alert 和c#中的MessageBox();
UIAlertView 继承自 UIView (@interface UIAlertView : UIView )
一、简单的初始化一个UIAlertView 对象。
UIAlertView* alert = [[UIAlertView alloc] init];
激活 alert ,让它显示。
[alert show];
结果将如下:
这样虽然出现了一个提示框,但是太不过友好,让人根本无法使用。
二,带有button的提示框。
UIAlertView 里面包含了另外一种用来初始化的方法。
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
带有一个button。
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"简单的提示框" message:@"simple alert" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
[alert show];
带有多个button
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"简单的提示框" message:@"simple alert" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"Button1",@"Button2",@"Button3" ,nil];
[alert show];
要想处理多个button点击之后做出不同响应,那么必须让当前控制器类遵循 UIAlertViewDelegate 协议。
UIAlertViewDelegate 里面包含了一个方法(- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;),用来触发在点击button之后的操作,判断是哪一个button 有两种方式,一种是更具button 的索引,
另外一种是button的title。
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString* buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Button1"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"Button2"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"Button3"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"ok"]){
userOutput.text = buttonTitle;
}
}
三 、给提示框添加输入框,最经典的案例,appstore 下载的时候输入密码、
首先,初始化UITextField
userInput = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 70.0, 260.0, 25.0)];
[userInput setBackgroundColor:[UIColor whiteColor ]];
将userInput 添加在 alert上,
[alert addSubview:userInput];
- (IBAction)btnWithTextField:(id)sender {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Please Enter Your Email Address" message:@"simple alert" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
userInput = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 70.0, 260.0, 25.0)];
[userInput setBackgroundColor:[UIColor whiteColor ]];
[alert addSubview:userInput];
[alert show];
[alert release];
[userInput release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSMutableString* buttonTitle = [NSMutableString stringWithString:[alertView buttonTitleAtIndex:buttonIndex]];
if([buttonTitle isEqualToString:@"Button1"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"Button2"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"Button3"]){
userOutput.text = buttonTitle;
}if([buttonTitle isEqualToString:@"ok"]){
[buttonTitle appendString:userInput.text];
userOutput.text = buttonTitle;
}
}