Четкого и информативного объяснения этому не нашел.
Где найти четкое объяснение быстрого оповещения (UIAlertController)?
Ответы (3)
После некоторого поиска по теме я не нашел четкого объяснения, даже в ссылке на его класс Справочник по UIAlertController
Это нормально, но недостаточно ясно для меня.
Итак, собрав немного миров, я решил сделать свое собственное объяснение (надеюсь, это поможет)
Итак, вот оно:
UIAlertView
устарел, как указано: UIAlertView в SwiftUIAlertController
следует использовать в iOS8+, поэтому, чтобы сначала создать его, нам нужно создать его экземпляр, конструктор (init) получает 3 параметра:
2.1 title:String -> текст, выделенный жирным шрифтом, для отображения в верхней части диалогового окна предупреждения
2.2 сообщение: Строка -> меньший текст (в значительной степени объясняет сам себя)
2.3 prefferedStyle:UIAlertControllerStyle
-> определить стиль диалогового окна, в большинстве случаев: UIAlertControllerStyle.Alert
Теперь, чтобы показать его пользователю, мы можем использовать
showViewController
или < a href="https://developer.apple.com/reference/uikit/uiviewcontroller/1621380-present" rel="noreferrer">presentViewController
и передайте наше предупреждение в качестве параметраЧтобы добавить некоторое взаимодействие с пользователем, мы можем использовать:
4.1 UIAlertController.addAction
для создания кнопок
4.2 UIAlertController.addTextField
для создания текстовых полей
Примечание к редактированию: примеры кода ниже, обновленные для синтаксиса swift 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: одно настраиваемое текстовое поле ввода и одна кнопка
@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's 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's Optional here
}
//event handler with predefined function
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));
present(alert, animated: true, completion: nil);
}
Надеюсь, это поможет, и удачи ;-)
Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish.
Лично я предпочитаю многоязычный стиль кода, поэтому вы видите его в моих примерах.
- person Nikita Kurtin; 02.12.2016
Экземпляр UIAlertController может быть представлен модально на экране так же, как и любой другой UIViewController с использованием метода presentViewController:animated:completion:. Что отличает экземпляр 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)
}
Часть синтаксиса изменилась по сравнению с оригинальными ответами. Вот пример кода, который предупреждает пользователя, если он не выполнил вход в 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")
}
}
UIAlertController
как для предупреждения, так и для листа действий. Я считаю, что примеры — самый простой способ понять, как все работает. Вот пример предупреждения, а вот пример списка действий. - person Suragch   schedule 04.06.2017