Написание обработчика для UIAlertAction
Я представляю пользователю UIAlertView
, и я не могу понять, как написать обработчик. Это моя попытка:
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: {self in println("Foo")})
Я получаю кучу проблем в Xcode.
В документации указано convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)
Все блоки/затворы немного на моей голове в данный момент. Любое предложение очень ценится.
Ответы
Ответ 1
Вместо self в вашем обработчике, поставьте (alert: UIAlertAction!). Это должно сделать ваш код похожим на
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: {(alert: UIAlertAction!) in println("Foo")}))
это правильный способ определения обработчиков в Swift.
Как указал Брайан ниже, есть также более простые способы определения этих обработчиков. Использование его методов обсуждается в книге, посмотрите раздел "Закрытия"
Ответ 2
Функции являются первоклассными объектами в Swift. Поэтому, если вы не хотите использовать закрытие, вы также можете просто определить функцию с соответствующей сигнатурой, а затем передать ее как аргумент handler
. Обратите внимание:
func someHandler(alert: UIAlertAction!) {
// Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: someHandler))
Ответ 3
Вы можете сделать это так просто, как с помощью быстрого 2:
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
self.pressed()
}))
func pressed()
{
print("you pressed")
}
или
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
print("pressed")
}))
Все приведенные выше ответы правильны, я просто показываю другой способ, который можно сделать.
Ответ 4
Предположим, что вы хотите получить UIAlertAction с основным заголовком, двумя действиями (сохранить и сбросить) и отменить кнопку:
let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
//Add Cancel-Action
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
//Add Save-Action
actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Save action...")
}))
//Add Discard-Action
actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Discard action ...")
}))
//present actionSheetController
presentViewController(actionSheetController, animated: true, completion: nil)
Это работает для быстрого 2 (Xcode Version 7.0 beta 3)
Ответ 5
Изменение синтаксиса в swift 3.0
alert.addAction(UIAlertAction(title: "Okay",
style: .default,
handler: { _ in print("Foo") } ))
Ответ 6
вот как я делаю это с xcode 7.3.1
// create function
func sayhi(){
print("hello")
}
//создаем кнопку
let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler: { action in
self.sayhi()})
//добавление кнопки в элемент управления предупреждением
myAlert.addAction(sayhi);
//весь код, этот код добавит 2 кнопки
@IBAction func sayhi(sender: AnyObject) {
let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler: { action in
self.sayhi()})
// this action can add to more button
myAlert.addAction(okAction);
myAlert.addAction(sayhi);
self.presentViewController(myAlert, animated: true, completion: nil)
}
func sayhi(){
// move to tabbarcontroller
print("hello")
}
Ответ 7
в swift4:
let alert = UIAlertController (title: "someAlert", сообщение: "someMessage", предпочитаемый стиль: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
_ in print("FOO ")
}))
присутствует (оповещение, анимация: правда, завершение: ноль)
Ответ 8
создать предупреждение, протестированное в xcode 9
let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)
и функция
func finishAlert(alert: UIAlertAction!)
{
}
Ответ 9
В Свифте
let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
// Write Your code Here
}
alertController.addAction(Action)
self.present(alertController, animated: true, completion: nil)
В объективе C
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
}];
[alertController addAction:OK];
[self presentViewController:alertController animated:YES completion:nil];
Ответ 10
Для реализации этого в Swift 4:
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Okay",style: UIAlertAction.Style.Default,
handler: {(alert: UIAlertAction!) in print("Foo")}))