When trying to reuse UIAlertAction
, it looks like the handler is being executed only once.
I've created a test project with an array of UIAlertAction
with 3 actions:
private var actions = [UIAlertAction]()
override func viewDidLoad() {
super.viewDidLoad()
var ac = UIAlertAction(title: "A",
style: .default) { (actioni) in
print("Selected A")
}
actions.append(ac)
ac = UIAlertAction(title: "B",
style: .default) { (actioni) in
print("Selected B")
}
actions.append(ac)
ac = UIAlertAction(title: "C",
style: .default) { (actioni) in
print("Selected C")
}
actions.append(ac)
}
@IBAction func runAction(_ sender: Any) {
let actionSheet = UIAlertController(title: nil,
message: nil,
preferredStyle: .actionSheet)
actions.forEach({
actionSheet.addAction($0)
})
self.present(actionSheet, animated: true) {
print("Done")
}
}
The array of actions is created once and not changed. Every time the button is pressed, an ActionSheet
is created and the unchanged actions are added.
However, the menu will only work the first time. If I recreate the actions they work as expected.
It looks like actions cannot be reused, although I did not see that being documented.
- Edit:
This was resolve here:
UIAlertController - Action not executed if alert dismissed the first time
By sending a copy()
of UIAlertAction
:
actions.forEach({
actionSheet.addAction($0.copy() as! UIAlertAction)
})
Question still valid, looks like the handler is not reusable.