IOS使用视图控制器和视图(一)显示提示 UIAlertView

来源:互联网 发布:淘宝的伴侣 一个桃子 编辑:程序博客网 时间:2024/06/05 11:16

UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Title"message:@"Message"delegate:nilcancelButtonTitle:@"Cancel"otherButtonTitles:@"Ok", nil];[alertView show];
PS:需要创建更多按键在otherButton中添加,以nil结尾。


需要知道被按下哪一个键

首先在视图控制器头文件中添加委托:

@interface Displaying_Alerts_with_UIAlertViewViewController: UIViewController <UIAlertViewDelegate>@end
创建UIAlertView时delegate置为self。

在实现文件中添加按键响应函数

- (void) alertView:(UIAlertView *)alertViewclickedButtonAtIndex:(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:selfcancelButtonTitle:@"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];}
上面代码效果如下:


0 0