自强学堂
自强学堂:学习、分享、让你更强!
IOS 教程HTMLCSSJAVASCRIPTJQUERYSQLPHPBOOTSTRAPANGULARXML
 

iOS警告对话框(Alerts)

IOS警告对话框的使用

警告对话框用来给用户提供重要信息。

仅在警告对话框视图中选择选项后,才能着手进一步使用应用程序。

重要的属性

  • alertViewStyle
  • cancelButtonIndex
  • delegate
  • message
  • numberOfButtons
  • title

重要的方法

- (NSInteger)addButtonWithTitle:(NSString *)title
- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex
- (void)dismissWithClickedButtonIndex:
  (NSInteger)buttonIndex animated:(BOOL)animated
- (id)initWithTitle:(NSString *)title message:
  (NSString *)message delegate:(id)delegate
  cancelButtonTitle:(NSString *)cancelButtonTitle 
  otherButtonTitles:(NSString*)otherButtonTitles, ...
- (void)show

更新 ViewController.h,如下所示

让类符合警告对话框视图的委托协议,如下所示,在ViewController.h中添加<UIAlertViewDelegate>

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIAlertViewDelegate>{
    
}
@end

添加自定义方法 addAlertView

-(void)addAlertView{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
    @"Title" message:@"This is a test alert" delegate:self 
    cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    [alertView show];
}

执行警告对话框视图的委托方法

#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:
  (NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            NSLog(@"Cancel button clicked");
            break;
        case 1:
            NSLog(@"OK button clicked");
            break;
        
        default:
            break;
    }
}

在 ViewController.m 中修改 viewDidLoad,如下所示

(void)viewDidLoad
{
   [super viewDidLoad];
   [self addAlertView];
}

输出

现在当我们运行该应用程序我们会看到下面的输出:

alertOutput1