iOS7、iOS8 Alert 更新转换

iOS7、iOS8 Alert 更新转换

UIAlertView UIAlertController

iOS7 在UI外观带来相当大的变格,但在iOS8上面则是将Framework增强许多,也将许多的Framework进行整合,然而UIAlertView则是其一,在iOS8之后,Apple将UIAlertView、UIActionSheet进行整合,取而代之的为UIAlertController,这带来的好处则是在iPad、iPhone不用再针对其特性来撰写专用的程式,这些底层都会帮你处理完成,虽然是如此,但还是要在旧版本上面做一些过度期、相容的动作。

iOS7 UIAlertView

iOS7 下要跳出Alert视窗的程式码如下:

//-----------start-----------
            UIAlertView *alertView =
            [[UIAlertView alloc] initWithTitle:@"Title"
                                       message:@"Message For iOS 7"
                                      delegate:nil
                             cancelButtonTitle:@"Close"
                             otherButtonTitles:nil];
            [alertView show];
//------------end------------

iOS8 UIAlertController

iOS 8 使用UIAlertController 来取代UIAlertView、UIActionSheet,使用方式也很容易:

//-----------start-----------
            UIAlertController *alertController =
            [UIAlertController alertControllerWithTitle:@"Title"
                                                message:@"Message For iOS8"
                                         preferredStyle:UIAlertControllerStyleAlert];
            // Close
            UIAlertAction *alertAction =
            [UIAlertAction actionWithTitle:@"Close"
                                     style:UIAlertActionStyleCancel
                                   handler:nil];
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
//------------end------------

版本判断与整合

//-----------start-----------
        if ([UIAlertController class]) {
            // iOS 8以上使用 UIAlertController
            UIAlertController *alertController =
            [UIAlertController alertControllerWithTitle:@"Title"
                                                message:@"Message For iOS8"
                                         preferredStyle:UIAlertControllerStyleAlert];
            // Close
            UIAlertAction *alertAction =
            [UIAlertAction actionWithTitle:@"Close"
                                     style:UIAlertActionStyleCancel
                                   handler:nil];
            [alertController addAction:alertAction];

            [self presentViewController:alertController animated:YES completion:nil];
        } else {
            // iOS7 以下
            UIAlertView *alertView =
            [[UIAlertView alloc] initWithTitle:@"Title"
                                       message:@"Message For iOS 7"
                                      delegate:nil
                             cancelButtonTitle:@"Close"
                             otherButtonTitles:nil];
            [alertView show];
        }
//------------end------------

目前iOS 8 还是能沿用iOS 7所提供的做法,所以在撰写时依照你自已的考量自行决定哪个方式比较适合。

延伸阅读

UIAlertController Changes in iOS 8

UIAlertController in iOS8 – 中文

Exploring UIAlertController