UIAlertView (警告视图)这个控件的应用领域非常广泛,是一个很实用的控件。
创建代码如下:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"标题" message:@"提示文本信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定1",@"确定2",@"确定N", nil];
[alert show];//显示alertView
按钮的数量可以自由设定,只有“取消”按钮也可以。
UIAlertView的作用一般是触发某个事件,或者点击了某个按钮才会弹出来,要由用户进一步进行选择,因此要在这些“选择”中绑定方法。
_alert = [[UIAlertView alloc] initWithTitle:@"不得了啦" message:@"你的娃哭了" delegate:self cancelButtonTitle:@"什么也不干" otherButtonTitles:@"打一顿",@"哄一哄",@"叫老婆来管",nil];
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {//点击按钮的,根据下标确定点了哪一个按钮
if (buttonIndex == 1) {//点击第一个按钮
NSLog(@"打一顿");
}else if (buttonIndex == 2) {//点击第二个
NSLog(@"哄一哄");
}
else if (buttonIndex == 3) {//点击第三个
NSLog(@"叫老婆来管");
}
else if (buttonIndex == 0) {//点击取消按钮
NSLog(@"取消啦");
}
}
注意各个按钮的下标,“取消”按钮的下标是0,“确定”按钮依次从1开始。
UIAlertViewStyle
UIAlertViewStyleDefault = 0,//默认
UIAlertViewStyleSecureTextInput,//带一个密码的输入框
UIAlertViewStylePlainTextInput,//普通输入框
UIAlertViewStyleLoginAndPasswordInput//账号密码 两个输入框
演示带账号密码的输入框
_alert = [[UIAlertView alloc] initWithTitle:@"登录" message:@"输入账号密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
_alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {//点击按钮的,根据下标确定点了哪一个按钮
if (buttonIndex == 0) {
NSLog(@"取消");
}else if (buttonIndex == 1) {
UITextField *field = [alertView textFieldAtIndex:0];//获取第一个框(账号)文本信息
UITextField *passwordField = [alertView textFieldAtIndex:1];//获取第二个框(密码)文本信息
NSLog(@"账号:%@\n密码:%@",field.text,passwordField.text);
}
效果如图所示
UIAlertView是个非常实用的控件,运用得当能增加用户体验,当然有时候也很烦,比如:各种app的(亲,给个好评把)。看自己把握。