2017-11-18 19 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) 
} 

私は別のUIAlertを呼び出すためにUIAlertActionのハンドラを使用しようとしています。出来ますか?

私は、次のエラーが発生します:

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

ハンドラはないコール機能にありません。 は、の関数です。

たとえば、これを行う可能性があります。

handler: jokeFinal 

にそしてそうに

handler: jokeFinal() 

を変更すると

func jokeFinal(_ action: UIAlertAction) { 

func jokeFinal() { 

の宣言を変更します。

関連する問題