I want to set up a UIAlertController
with four action buttons, and the titles of the buttons to be set to "hearts", "spades", "diamonds", and "clubs". When a button is pressed, I want to return its title.
In short, here is my plan:
// TODO: Create a new alert controller
for i in ["hearts", "spades", "diamonds", "clubs"] {
// TODO: Add action button to alert controller
// TODO: Set title of button to i
}
// TODO: return currentTitle() of action button that was clicked
Try this:
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert)
for i in ["hearts", "spades", "diamonds", "hearts"] {
alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething)
}
self.presentViewController(alert, animated: true, completion: nil)
And handle the action here:
func doSomething(action: UIAlertAction) {
//Use action.title
}
For future reference, you should take a look at Apple's Documentation on UIAlertControllers
here´s a sample code with two actions plus and ok-action:
import UIKit
// The UIAlertControllerStyle ActionSheet is used when there are more than one button.
@IBAction func moreActionsButtonPressed(sender: UIButton) {
let otherAlert = UIAlertController(title: "Multiple Actions", message: "The alert has more than one action which means more than one button.", preferredStyle: UIAlertControllerStyle.ActionSheet)
let printSomething = UIAlertAction(title: "Print", style: UIAlertActionStyle.Default) { _ in
print("We can run a block of code." )
}
let callFunction = UIAlertAction(title: "Call Function", style: UIAlertActionStyle.Destructive, handler: myHandler)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
// relate actions to controllers
otherAlert.addAction(printSomething)
otherAlert.addAction(callFunction)
otherAlert.addAction(dismiss)
presentViewController(otherAlert, animated: true, completion: nil)
}
func myHandler(alert: UIAlertAction){
print("You tapped: \(alert.title)")
}}
with i.E. handler: myHandler you define a function, to read the result of the let printSomething.
This is just one way ;-)
Any questions?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With