Reputation: 2297
In order to manage/shorten my code a little, I decided to try to create a helper class to manage all alerts.
The idea is that the helper class will create the alert. When the user presses the button, it will then send a callback to inform the code on the viewController which button is pressed. Then based on that I can fire different bits of code.
Currently the code I have manages to pop up the alert correctly, but I cannot get it to send the callback when the button is pressed.
here is my alert manager I created so far(still basic for simplicity):
var alertMgr: alertManager = alertManager()
class alertManager: NSObject {
func showAlert(titleText:String?, confirmText:String, cancelText:String, msgText:String, showCancel:Bool, showConfirm:Bool, style:UIAlertControllerStyle, viewController:UIViewController) -> Int? {
let alertController = UIAlertController(title: titleText, message: msgText, preferredStyle: style)
var myInt:Int!
let actionLeft = UIAlertAction(title:cancelText, style: .Cancel) { action in
println("0") //works when user presses cancel button
myInt = 0
}
let actionRight = UIAlertAction(title:confirmText, style: .Default) { action in
println("1") //works when user presses confirm button
myInt = 1
}
alertController.addAction(actionLeft)
alertController.addAction(actionRight)
viewController.presentViewController(alertController, animated: true, completion: nil)
return myInt //does not return when button is pressed???
}
}
In my code when I want to show an alert I use the following code:
let titleTxt:String = "title txt goes here."
let confirmTxt:String = "confirm"
let cancelTxt:String = "cancel"
let msgTxt:String = "some msg goes here."
let showCancel:Bool = true
let showConfirm:Bool = true
let style:UIAlertControllerStyle = .ActionSheet
let alert = alertMgr.showAlert(titleTxt, confirmText: confirmTxt, cancelText: cancelTxt, msgText: msgTxt, showCancel: showCancel, showConfirm: showConfirm, style:style, viewController: self)
switch alert as Int! {
case nil:
println("nil value")
case 0:
println("cancel pressed") //never gets fired. when button is pressed
case 1:
println("confirm pressed") //never gets fired. when button is pressed
default:
break
}
The main problem is I cannot seem to get the call back to send the "myInt" value on button press. I have searched through pretty much all questions on here with [UIAlertController] and have not been able to find any hints that would push me in the right direction.
Any help would be great.
Upvotes: 2
Views: 918
Reputation: 8944
showAlert
returns the value of myInt
before any of the given blocks gets a chance to be executed, the solution is to pass complete action-blocks as parameters of showAlert
. In order to shorten the signature you can prepare a special type with text, block and flag values and make the function to process arrays of the objects of this type.
Upvotes: 2