提醒功能实现:UIAlertController与UIAlertAction
苹果自iOS8开始,就已经废弃了之前用于界面提醒的UIAlertView类以及UIActionSheet,取而代之的是UIAlertController以及UIAlertAction,从实际使用情况来看,苹果把之前不同类型/样式的通知实现方法进行了统一,简化了有关提醒功能的实现。
1、UIAlertController的使用
- 常用方法与属性
+ (instancetype)alertControllerWithTitle:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle; //初始化
- (void)addAction:(UIAlertAction *)action;//添加一个按钮选项
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0);//显示提醒
- 提醒的样式把弹出提醒和底部提醒进行了统一,使用preferredStyle来区分
typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
UIAlertControllerStyleActionSheet = 0,
UIAlertControllerStyleAlert
}
2、UIAlertAction的使用
- UIAlertAction是定义提醒中每个按钮的样式以及用户点击后所执行的操作
+ (instancetype)actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction *action))handler;
- 提醒按钮的样式是通过UIAlertActionStyle参数决定的
typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
UIAlertActionStyleDefault = 0,
UIAlertActionStyleCancel,
UIAlertActionStyleDestructive
} NS_ENUM_AVAILABLE_IOS(8_0);
3、示例代码
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要重新开始?" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
self.timeLabel.text = @"5"; }];
UIAlertAction* Action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
[alert addAction:defaultAction];
[alert addAction:Action1];
[self presentViewController:alert animated:YES completion:nil];