2017-11-18 70 views
-2

是否可以使用处理程序触发其他警报?如何使用UIAlertAction的“处理程序”调用另一个UIAlertAction?

func jokeFinal() { 
    let alert = UIAlertController(title: "Never Mind", message: "It's Pointless", preferredStyle: .alert) 
    let action = UIAlertAction(title: "Hahahahahaha", style: .default, handler: nil) 
    alert.addAction(action) 
    present(alert, animated: true, completion: nil) 
} 

func joke() { 
    let alert = UIAlertController(title: "A broken pencil", message: "...", preferredStyle: .alert) 
    let action = UIAlertAction(title: "A broken pencil who?", style: .default, handler: jokeFinal()) 
    alert.addAction(action) 
    present(alert, animated: true, completion: nil) 
} 

@IBAction func nock() { 
    let alert = UIAlertController(title: "Knock,Knock", message: "..", preferredStyle: .alert) 
    let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke()) 
    alert.addAction(action) 
    present(alert, animated: true, completion: nil) 
} 

我试图用一个UIAlertAction的处理程序调用另一个UIAlert。可能吗?

我收到以下错误:

Cannot convert value of type '()' to expected argument type '((UIAlertAction) -> Void)?'

回答

0

当然可以!这是可能的。尝试类似的东西:

let alertController = UIAlertController.init(title: "Title", message: "Message", preferredStyle: .alert) 
alertController.addAction(UIAlertAction.init(title: "Title", style: .default, handler: { (action) in 
     self.someFunction() 
})) 
self.present(alertController, animated: true, completion: nil) 

这里是你的函数:

func someFunction() { 
    let alertController = UIAlertController.init(title: "Some Title", message: "Some Message", preferredStyle: .alert) 
    alertController.addAction(UIAlertAction.init(title: "Title For Button", style: .default, handler: { (action) in 
     // Completion block 
    })) 
    self.present(alertController, animated: true, completion: nil) 
} 

这里是你的问题行:

let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke()) 

你可以很容易地改变它:

let action = UIAlertAction(title: "Who's there??", style: .default, handler: { (action) in 
     // Completion block 
}) 

希望能帮助到你!

0

的处理程序不通话功能。它的一个函数。

所以,例如,你可能会这样做。的

func jokeFinal() { 

声明更改为

func jokeFinal(_ action: UIAlertAction) { 

然后改变

handler: jokeFinal() 

handler: jokeFinal 

等。

相关问题