Подтвердить что ты не робот

Где найти четкое объяснение относительно быстрого предупреждения (UIAlertController)?

Не удалось найти ясное и информативное объяснение этого.

4b9b3361

Ответ 1

После некоторого времени поиска по теме я не найти четкое объяснение, даже в нем ссылка на класс Справка UIAlertController

Это нормально, но недостаточно ясно для меня.

Итак, собрав несколько моментов, я решил сделать свое объяснение (Надеюсь, что это поможет)

Итак, вот оно:

  • UIAlertView устарел, как указано: UIAlertView в Swift
  • UIAlertController следует использовать в iOS8 + поэтому для создания первой нужно создать экземпляр, конструктор (init) получает 3 параметра:

2.1 title: String → полужирный текст для отображения в верхней части диалогового окна предупреждения

2.2 сообщение: String → меньший текст (в значительной степени объясняет это сам)

2.3 prefferedStyle:UIAlertControllerStyle → определить стиль диалогового окна, в большинстве случаев: UIAlertControllerStyle.Alert

  1. Теперь, чтобы показать это пользователю, мы можем использовать showViewController или presentViewController и передать наше предупреждение как параметр

  2. Чтобы добавить какое-то взаимодействие с пользователем, мы можем использовать:

4,1   UIAlertController.addAction для создания кнопок

4,2 UIAlertController.addTextField для создания текстовых полей

Изменить примечание: примеры кода ниже, обновлены для синтаксиса быстрого 3

Пример 1: простой диалог

@IBAction func alert1(sender: UIButton) {
     //simple alert dialog
    let alert=UIAlertController(title: "Alert 1", message: "One has won", preferredStyle: UIAlertControllerStyle.alert);
    //show it
    show(alert, sender: self);
}

Пример 2: диалог с одним входным текстовым полем и двумя кнопками

@IBAction func alert2(sender: UIButton) {
    //Dialog with one input textField & two buttons
    let alert=UIAlertController(title: "Alert 2", message: "Two will win too", preferredStyle: UIAlertControllerStyle.alert);
    //default input textField (no configuration...)
    alert.addTextField(configurationHandler: nil);
    //no event handler (just close dialog box)
    alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil));
    //event handler with closure
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
        let fields = alert.textFields!;
        print("Yes we can: "+fields[0].text!);
    }));
    present(alert, animated: true, completion: nil);
}

Пример 3. Один настраиваемый входной текстField и одна кнопка

@IBAction func alert3(sender: UIButton) {
   // one input & one button
   let alert=UIAlertController(title: "Alert 3", message: "Three will set me free", preferredStyle: UIAlertControllerStyle.alert);

    //configured input textField
    var field:UITextField?;// operator ? because it been initialized later
    alert.addTextField(configurationHandler:{(input:UITextField)in
        input.placeholder="I am displayed, when there is no value ;-)";
        input.clearButtonMode=UITextFieldViewMode.whileEditing;
        field=input;//assign to outside variable(for later reference)
    });
    //alert3 yesHandler -> defined in the same scope with alert, and passed as event handler later
    func yesHandler(actionTarget: UIAlertAction){
        print("YES -> !!");
        //print text from 'field' which refer to relevant input now
        print(field!.text!);//operator ! because it Optional here
    }
    //event handler with predefined function
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));

    present(alert, animated: true, completion: nil);
 }

Надеюсь, это поможет, и удачи; -)

Ответ 2

Экземпляр UIAlertController может быть представлен на экране точно так же, как и любой другой UIViewController, используя метод presentViewController: анимированный: завершение:. Что делает экземпляр UIAlertController дифференцированным между работой в ActionSheet или как AlertView, является параметр стиля, который вы передаете при его создании.

Больше делегирования

Если вы использовали UIActionSheet или UIAlertView, вы знаете, что способ получить обратный вызов от него - это класс (в большинстве случаев ViewController) для реализации протокола UIActionSheetDelegate или UIAlertViewDelegate. Есть несколько проектов с открытым исходным кодом, которые заменили этот шаблон делегирования на блокированные обратные вызовы, но официальные API никогда не обновлялись. UIAlertController не использует делегирование. Вместо этого он имеет набор элементов UIAlertAction, которые используют замыкания (или блоки, если вы используете Objective-C) для обработки ввода пользователя.

В листе действий

@IBAction func showActionSheet(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", preferredStyle: .ActionSheet)

  //Create and add the Cancel action
  let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
    //Just dismiss the action sheet
  }
  actionSheetController.addAction(cancelAction)
    //Create and add first option action
  let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in
    //Code for launching the camera goes here
    }
  actionSheetController.addAction(takePictureAction)
  //Create and add a second option action
  let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in
    //Code for picking from camera roll goes here
    }
  actionSheetController.addAction(choosePictureAction)

  //Present the AlertController
  self.presentViewController(actionSheetController, animated: true, completion: nil)
}

Для AlertView с текстовым полем

@IBAction func showAlert(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)

  //Create and add the Cancel action
  let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
    //Do some stuff
    }
  actionSheetController.addAction(cancelAction)
    //Create and an option action
  let nextAction: UIAlertAction = UIAlertAction(title: "Next", style: .Default) { action -> Void in
    //Do some other stuff
    }
  actionSheetController.addAction(nextAction)
  //Add a text field
  actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
       //TextField configuration
     textField.textColor = UIColor.blueColor()
   }

   //Present the AlertController
   self.presentViewController(actionSheetController, animated: true, completion: nil)
}

Ответ 3

Часть синтаксиса изменилась с момента первоначального ответа. Вот пример кода, который предупреждает пользователя, если они не вошли в iCloud.

CKContainer.default().accountStatus { (accountStatus, error) in
            switch accountStatus {
            case .available:
                print("iCloud Available")
            case .noAccount:
                print("No iCloud account")
                //simple alert dialog
                let alert=UIAlertController(title: "Sign in to iCloud", message: "This application requires iClound. Sign in to your iCloud account to write records. On the Home screen, launch Settings, tap iCloud, and enter your Apple ID. Turn iCloud Drive on. If you don't have an iCloud account, tap Create a new Apple ID", preferredStyle: UIAlertControllerStyle.alert);
                //no event handler (just close dialog box)
                alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil));
                //show it
                self.present(alert, animated: true, completion: nil)
            case .restricted:
                print("iCloud restricted")
            case .couldNotDetermine:
                print("Unable to determine iCloud status")
            }
        }