UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
[alertView show];
PS:需要创建更多按键在otherButton中添加,以nil结尾。
需要知道被按下哪一个键
首先在视图控制器头文件中添加委托:
@interface Displaying_Alerts_with_UIAlertViewViewController
: UIViewController <UIAlertViewDelegate>
@end
创建UIAlertView时delegate置为self。
在实现文件中添加按键响应函数
- (void) alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:[self yesButtonTitle]]){
NSLog(@"User pressed the Yes button.");
}
else if ([buttonTitle isEqualToString: [self noButtonTitle]]){
NSLog(@"User pressed the No button.");
}
}
该函数传入的是被按下的按键的索引buttonIndex,[alertView buttonTitleAtIndex:buttonIndex]获得的是被按下按键的标题。
需要输入一些信息则修改样式
typedef enum {
UIAlertViewStyleDefault = 0, //默认样式
UIAlertViewStyleSecureTextInput, //密码输入样式
UIAlertViewStylePlainTextInput, //一个简单输入框样式
UIAlertViewStyleLoginAndPasswordInput //账号密码输入样式
} UIAlertViewStyle;
- (void) viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Credit Card Number"
message:@"Please enter your credit card number:"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
[alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
/* Display a numerical keypad for this text field */
UITextField *textField = [alertView textFieldAtIndex:0];//获得输入的信息
textField.keyboardType = UIKeyboardTypeNumberPad; //输入键盘样式
[alertView show];
}
上面代码效果如下: