2016-10-15 2 views
16

У меня есть следующий метод оповещения.UIAlertController не работает с Swift 3.0

static func notifyUser(_ title: String, message: String) -> Void 
{ 
    let alert = UIAlertController(title: title, 
            message: message, 
            preferredStyle: UIAlertControllerStyle.alert) 

    let cancelAction = UIAlertAction(title: "OK", 
            style: .cancel, handler: nil) 

    alert.addAction(cancelAction) 
    self.presentViewController(alert, animated: true, completion: nil) 
} 

Я получаю сообщение об ошибке сказав, что есть дополнительный аргумент animated в методе presentViewController, но когда я беру его, он все равно не освобождает ошибку, а потом я сказал, что completion является дополнительный аргумент.

ответ

26

presentViewController изменен в Swift 3 следующим образом.

present(alert, animated: true) 

Проверьте, пожалуйста, Apple Documentation.

От Swift 3 completion не является обязательным, поэтому, если вы не хотите обрабатывать блок завершения, вам не нужно писать nil, и если вы хотите обработать блок завершения, напишите вот так.

self.present(alert, animated: true) { 

} 

Примечание: Ваш метод notifyUser объявлен с static, так что вы не можете использовать self с ним так, что удалить и удалить следующую ошибку, которую вы получите после исправления этой.

+3

Благодаря человеку. Весь этот быстрый 3 имеет меня боком! Я ценю это! – BlackHatSamurai

+0

@BlackHatSamurai Welcome mate :) –

+0

Ваше решение стандартно, но ваш ответ не соответствует вопросу. Он пытается представить контроллер вида, используя self, в статическом методе. вот почему он получает ошибку завершения - дополнительный аргумент –

26
let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", preferredStyle: .alert) 
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in 
      //Just dismiss the action sheet 
     } 
actionSheetController.addAction(cancelAction) 
self.present(actionSheetController, animated: true, completion: nil) 
+0

OP работает с Swift 3 Так что это не поможет. –

+0

Я просто изменил его в swift 3.0, дайте мне 5 минут @NiravD –

+0

@NiravD сделал это –

11

Swift 3

let alertView = UIAlertController(title: "", message: "your message", preferredStyle: .alert) 
let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in 

}) 
alertView.addAction(action) 
self.present(alertView, animated: true, completion: nil) 
2

Swift 3 Попробуйте Пользовательские Действие Отменить

let uiAlertController = UIAlertController(// create new instance alert controller 
      title: "You TITLE text", 
      message: "You Message text", 
      preferredStyle:.alert) 

    uiAlertController.addAction(// add Custom action on Event is Cancel 
    UIAlertAction.init(title: "Cancel", style: .default, handler: { (UIAlertAction) in 
     //TO DO code 
     uiAlertController.dismiss(animated: true, completion: nil)//dismiss show You alert, on click is Cancel 
    })) 
    //show You alert 
    self.present(uiAlertController, animated: true, completion: nil) 
4

Вы пытаетесь использовать себя в статическом методе в то время как само должно быть текущим экземпляр этого класса, но static не может использовать self.

Без действий обработчика кнопки оповещения

В Obj-C

+(void) notifyUser:(NSString *)title withMessage:(NSString *)message onViewController:(UIViewController *)vc { 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; 
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]; 
    [alert addAction:action]; 
    //vc will be the view controller on which you will present your alert as you cannot use self because this method is static. 
    [vc presentViewController:alert animated:true completion:nil]; 
} 

В Swift 3,0

static func notifyUser(_ title: String, message: String, vc: UIViewController) -> Void 
    { 
     let alert = UIAlertController(title: title, 
             message: message, 
             preferredStyle: UIAlertControllerStyle.alert) 

     let cancelAction = UIAlertAction(title: "OK", 
             style: .cancel, handler: nil) 

     alert.addAction(cancelAction) 
     //vc will be the view controller on which you will present your alert as you cannot use self because this method is static. 
     vc.present(alert, animated: true, completion: nil) 
    } 

с действием обработчиком кнопки оповещения

В Obj-C

+(void) notifyUser:(NSString *)title withMessage:(NSString *)message withButtonTitles:(NSArray<NSString *> *)buttonTitles andButtonStyles:(NSArray *)styles onViewController:(UIViewController *)vc onCompletion:(void (^)(NSInteger))completion { 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; 

    for (NSString *title in buttonTitles) { 
     UIAlertActionStyle style = [[styles objectAtIndex:[buttonTitles indexOfObject:title]] intValue]; 

     UIAlertAction *actionObj = [UIAlertAction actionWithTitle:title style:style handler:^(UIAlertAction *action){ 
      NSInteger index = [buttonTitles indexOfObject:action.title]; 
      completion(index); 
     }]; 
     [alert addAction:actionObj]; 
    } 
    //vc will be the view controller on which you will present your alert as you cannot use self because this method is static. 
    [vc presentViewController:alert animated:true completion:nil]; 
} 

Invoke выше метод экземпляра, как это.

[ClassName notifyUser:@"Title For Alert" withMessage:@"Message for Alert" withButtonTitles:@[@"Camera",@"Library",@"Dismiss"] andButtonStyles:@[@(UIAlertActionStyleDefault),@(UIAlertActionStyleDefault),@(UIAlertActionStyleCancel)] onViewController:yourViewController onCompletion:^(NSInteger indexOfTappedButton){ 
        //Note the index of the button will have the same order as you have provide the titles array in this method 
    }]; 

Здесь yourViewController является контроллер, на котором вы представите это оповещение

В Swift 3.0

extension UIAlertController { 
    static func notifyUser(_ title: String, message: String, alertButtonTitles: [String], alertButtonStyles: [UIAlertActionStyle], vc: UIViewController, completion: @escaping (Int)->Void) -> Void 
    { 
     let alert = UIAlertController(title: title, 
             message: message, 
             preferredStyle: UIAlertControllerStyle.alert) 

     for title in alertButtonTitles { 
      let actionObj = UIAlertAction(title: title, 
              style: alertButtonStyles[alertButtonTitles.index(of: title)!], handler: { action in 
              completion(alertButtonTitles.index(of: action.title!)!) 
      }) 

      alert.addAction(actionObj) 
     } 


     //vc will be the view controller on which you will present your alert as you cannot use self because this method is static. 
     vc.present(alert, animated: true, completion: nil) 
    } 
} 

Invoke выше статический метод, как это.

UIAlertController.notifyUser("Title for Alert", message: "Message show in Alert", alertButtonTitles: ["Camera", "Library","Dismiss"], alertButtonStyles: [.default,.default,.cancel], vc: yourViewController, completion: { indexOfTappedButton in 
      //Note the index of the button will have the same order as you have provide the titles array in this method 
     }) 

Здесь yourViewController является контроллер, на котором вы представите это оповещение

+0

Если вы посмотрите на его код, вы поймете, что он хочет показать оповещение в статическом методе, но его заголовок показывает, что он также хочет, чтобы решение было быстрым. 3. Я завершаю оба. –

+0

Здесь вы идете. Я отметил ваш ответ. –

+0

Это не о голосовании или голосовании по голосу. Это вопрос. Я только что предложил решение об ошибке, которое опубликовано в вопросе не что-то еще. –

Смежные вопросы