OC 中的 Alerts函数

首页 / iOS入门教程 / OC 中的 Alerts函数

Alert用于向用户提供重要信息。只有在Alert视图中选择了选项,我们才能进一步使用该应用程序。

Alerts - 重要属性

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

Alerts - 重要方法

- (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-

通过添加<UIAlertViewDelegate>来使您的类符合警报视图委托协议,如ViewController.h中所示。

#import <UIKit/UIKit.h>

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

Alerts - 自定义方法

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

Alerts - 委托方法

#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];
}

运行应用程序时,将获得以下输出-

iOS Tutorial

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

程序员的数学基础课 -〔黄申〕

重学前端 -〔程劭非(winter)〕

Linux内核技术实战课 -〔邵亚方〕

技术管理案例课 -〔许健〕

人人都用得上的写作课 -〔涵柏〕

Spring编程常见错误50例 -〔傅健〕

零基础入门Spark -〔吴磊〕

AI绘画核心技术与实战 -〔南柯〕

好记忆不如烂笔头。留下您的足迹吧 :)