iOS——UIAlertController

本文详细介绍了iOS 8中新引入的UIAlertController及其关联类UIAlertAction。UIAlertController整合了UIAlertView和UIActionSheet的功能,提供了更灵活的对话框和操作表配置选项。文章还探讨了UIAlertController的各种属性和方法,包括如何创建、配置和显示UIAlertController,以及如何添加和定制UIAlertAction。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、UIAlertController

1. 概述

UIAlertController 是 iOS 8 的新特性之一,将原来的 UIAlertView(对话框)和 UIActionSheet(上拉菜单)结合在了一起;置于使用哪一个,取决于创建时指定它们的风格

UIAlertController 直接继承 UIViewController,所以它是一个视图控制器

2. 属性

1)创建 UIAlertController 的类方法,指定标题、消息以及风格样式

+ (instancetype)alertControllerWithTitle:(nullableNSString *)title message:(nullableNSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle;

typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
    UIAlertControllerStyleActionSheet = 0,  // 上拉菜单样式
    UIAlertControllerStyleAlert             // 对话框样式,默认样式
} NS_ENUM_AVAILABLE_IOS(8_0);


2)设置 UIAlertController 的标题

@property (nullable,nonatomic, copy)NSString *title;


3)设置 UIAlertController 的消息

@property (nullable,nonatomic, copy)NSString *message;


4)保存 UIAlertController 的风格样式,只能在初始化时设置

@property (nonatomic,readonly) UIAlertControllerStyle preferredStyle;


5)向 UIAlertController 对象添加动作按钮

- (void)addAction:(UIAlertAction *)action;


6)保存 UIAlertController 对象的所有动作按钮的数组

@property (nonatomic,readonly) NSArray<UIAlertAction *> *actions;


7)向 UIAlertController 对象添加文本框对象,并设置文本框的代码块

- (void)addTextFieldWithConfigurationHandler:(void (^__nullable)(UITextField *textField))configurationHandler;


8)保存 UIAlertController 对象的所有文本框的数组

@property (nullable,nonatomic, readonly)NSArray<UITextField *> *textFields;


9)优先选择的按钮;将该属性设置为某个动作按钮时,该按钮会加粗显示

@property (nonatomic, strong, nullable) UIAlertAction *preferredAction NS_AVAILABLE_IOS(9_0);


当在一个视图控制器中系那是另一个视图控制器时,可以使用方法

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0);

此方法只在没有 UINavigationController 时使用



二、UIAlertAction

1. 概述

UIAlertAction 用于向 UIAlertController 对象中添加动作按钮


2. 属性

1)创建 UIAlertAction 的类方法,并设置标题、风格、以及设置的代码块

+ (instancetype)actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction *action))handler;

typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
    UIAlertActionStyleDefault = 0,  // 默认风格
    UIAlertActionStyleCancel,       // 取消风格
    UIAlertActionStyleDestructive   // 警示风格,以红色字显示
} NS_ENUM_AVAILABLE_IOS(8_0);


2)获取动作按钮的标题

@property (nullable, nonatomic, readonly) NSString *title;


3)获取动作按钮的风格

@property (nonatomic, readonly) UIAlertActionStyle style;


4)设置动作按钮是否激活

@property (nonatomic, getter=isEnabled) BOOL enabled;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值