UIAlertView/UIAlertController iOS 7 and iOS 8 compatibility

后端 未结 14 1548
暗喜
暗喜 2020-11-28 22:31

I am using Swift to write an app and I need to show an alert. The app must be iOS 7 and iOS 8 compatible. Since UIAlertView has been replaced with UIAlert

14条回答
  •  日久生厌
    2020-11-28 23:00

    For non-swift code, pure objective-C do this

    if ([UIAlertController class])
        {
            // use UIAlertController
            UIAlertController *alert= [UIAlertController
                                          alertControllerWithTitle:@"Enter Folder Name"
                                          message:@"Keep it short and sweet"
                                          preferredStyle:UIAlertControllerStyleAlert];
    
            UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action){
                                                           //Do Some action here
                                                           UITextField *textField = alert.textFields[0];
                                                           NSLog(@"text was %@", textField.text);
    
                                                       }];
            UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
    
                                                               NSLog(@"cancel btn");
    
                                                               [alert dismissViewControllerAnimated:YES completion:nil];
    
                                                           }];
    
            [alert addAction:ok];
            [alert addAction:cancel];
    
            [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                textField.placeholder = @"folder name";
                textField.keyboardType = UIKeyboardTypeDefault;
            }];
    
            [self presentViewController:alert animated:YES completion:nil];
    
        }
        else
        {
            // use UIAlertView
            UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"Enter Folder Name"
                                                             message:@"Keep it short and sweet"
                                                            delegate:self
                                                   cancelButtonTitle:@"Cancel"
                                                   otherButtonTitles:@"OK", nil];
    
            dialog.alertViewStyle = UIAlertViewStylePlainTextInput;
            dialog.tag = 400;
            [dialog show];
    
        }
    

提交回复
热议问题