iOS底部弹出选择菜单:UIAlertController——UIActionSheet

作者: iOS 发布时间: 2021-03-30 浏览: 1999 次 编辑

本文代码源于自己的项目,亲测可行,简单易上手。

我们知道,从iOS8后,已经使用UIAlertController来取代UIAlertView和UIAlertSheet。

弹出菜单的方法,实现如下:

-(void)creatActionSheet {
    /*
     先创建UIAlertController,preferredStyle:选择UIAlertControllerStyleActionSheet,这个就是相当于创建8.0版本之前的UIActionSheet;
     
     typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
     UIAlertControllerStyleActionSheet = 0,
     UIAlertControllerStyleAlert
     } NS_ENUM_AVAILABLE_IOS(8_0);
     */
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"选择对象" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    /*
     typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
     UIAlertActionStyleDefault = 0,
     UIAlertActionStyleCancel,         取消按钮
     UIAlertActionStyleDestructive     破坏性按钮,比如:“删除”,字体颜色是红色的
     } NS_ENUM_AVAILABLE_IOS(8_0);
     
     */
    // 创建action,这里action1只是方便编写,以后再编程的过程中还是以命名规范为主
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"A类" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"选择了A类" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"B类" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"选择了B类" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    //把action添加到actionSheet里
    [actionSheet addAction:action1];
    [actionSheet addAction:action2];
    [actionSheet addAction:action3];
    
    //相当于之前的[actionSheet show];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

选择了哪一类后的动作可以在block里面实现。就自己修改代码啦~~

大概效果图(因为项目隐私,就不截自己的图了):