iOS - 消息弹框Alert

说明

UIAlertView 在iOS9.0已被废弃,应使用UIAlertController代替。

头文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    //UIAlertView* v;
    //定义弹框
    UIAlertController* _ac;
}
//定义弹框属性
@property(nonatomic, retain)UIAlertController * ac;
@end

源文件

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize ac = _ac;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100, 100, 100, 100);
    btn.backgroundColor = [UIColor orangeColor];
    [btn setTitle:@"弹框" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

-(void) onClick:(UIButton*) btn{
    NSLog(@"点击了%@",btn.currentTitle);
    [self alert];
}

-(void) alert{
    //UIAlertView已在iOS9废弃,应使用UIAlertController
    //构建UIAlertController,基于标题、消息、样式
    _ac = [UIAlertController alertControllerWithTitle:@"title" message:@"msg" preferredStyle:UIAlertControllerStyleAlert];
    //构建一个字符串数组
    NSArray* arr = @[@"a",@"b",@"c",@"d",@"e"];
    //获得数组长度
    NSInteger count = [arr count];
    //遍历数组,创建每一个UIAlertAction*,即:元素、动作
    //弹框添加刚创建的UIAlertActon
    for(int i=0; i<count; i++){
        UIAlertAction* action = [UIAlertAction actionWithTitle:arr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击事件输出文本
            NSLog(@"%@",arr[i]);
        }];
        [_ac addAction:action];
    }
    //展示弹框view
    [self presentViewController:_ac animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文/于小七 毕业典礼刚结束,寝室内乱七八糟,大家都忙着收拾东西。 杨科装好箱子回过身漫不经心的说:“我爸已经给我安...
    于小七阅读 3,652评论 4 8
  • 姓名:潘吉安 公司:宁波大发化纤有限公司 【日精进打卡第24天】 【知~学习】 《六项精进》大纲3遍 《大学》9遍...
    潘吉安阅读 715评论 0 0
  • 陆兄体健不怕凉, 迎着微寒著诗章。 虽然天气有点冷, 不穿长衫也无妨。
    小车16阅读 1,410评论 0 0