How do I pass more parameters to a UIAlertAction's handler? - ios

Is there any way to pass the array "listINeed" to the handler function "handleConfirmPressed"? I was able to do this by adding it as a class variable but that seemed very hacky and now I want to do this for multiple variables so I need a better solution.
func someFunc(){
//some stuff...
let listINeed = [someObject]
let alert = UIAlertController(title: "Are you sure?", message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed))
presentViewController(alert, animated: true, completion: nil)
}
func handleConfirmPressed(action: UIAlertAction){
//need listINeed here
}

The easiest way is to just pass a closure to the UIAlertAction constructor:
func someFunc(){
//some stuff...
let listINeed = [ "myString" ]
let alert = UIAlertController(title: "Are you sure?", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler:{ action in
// whatever else you need to do here
print(listINeed)
}))
presentViewController(alert, animated: true, completion: nil)
}
If you really want to isolate the functional part of the routine, you can always just put:
handleConfirmPressedAction(action:action, needed:listINeed)
into the callback block
A slightly more obscure syntax, that would retain the feel of a function both in passing it to the completion routine and in the callback function itself would be to define handleConfirmPressed as a curried function:
func handleConfirmPressed(listINeed:[String])(alertAction:UIAlertAction) -> (){
print("listINeed: \(listINeed)")
}
and then you can addAction using:
alert.addAction(UIAlertAction(title: "Confirm", style: .Destructive, handler: handleConfirmPressed(listINeed)))
Note that the curried function is shorthand for:
func handleConfirmPressed(listINeed:[String]) -> (alertAction:UIAlertAction) -> () {
return { alertAction in
print("listINeed: \(listINeed)")
}
}

I think this is easier.
class MyUIAlertAction: UIAlertAction {
var params: [String: Any] = [:]
}
func someFunc(){
//some stuff...
let listINeed = [ "myString" ]
let alert = UIAlertController(title: "Are you sure?", message: "message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
let action = MyUIAlertAction(title: "Confirm", style: .destructive, handler:{ (action: UIAlertAction) in
if let myaction = action as? MyUIAlertAction {
let listINeed = myaction.params["listINeed"] as? [String] ?? []
// whatever else you need to do here
print(listINeed)
}
})
action.params["listINeed"] = listINeed
alert.addAction(action)
}

Related

waiting for users response in swift

I created an alert:
var a = 0 // default
let userAction = UIAlertController(title: "Select", message: "Select an action", preferredStyle: UIAlertControllerStyle.alert)
userAction.addAction(UIAlertAction(title: "action 1", style: .default, handler: { (action: UIAlertAction!) in
a = 1
}))
userAction.addAction(UIAlertAction(title: "action 2", style: .cancel, handler: { (action: UIAlertAction!) in
a = 2
}))
present(userAction, animated: true, completion: nil)
let resp = Just.get("http://localhost/\(a)").text
return resp
and after this code i'm sending a request with a parameter(a) but request is sent before choosing an action.
how can i wait till user choose and action from alert?
Remove your call function below the present call. Move it to your alert button action closure
var a = 0 // default
let userAction = UIAlertController(title: "Select", message: "Select an
action", preferredStyle: UIAlertControllerStyle.alert)
userAction.addAction(UIAlertAction(title: "action 1", style: .default,
handler: { (action: UIAlertAction!) in
a = 1
// Call function here
}))
userAction.addAction(UIAlertAction(title: "action 2", style: .cancel,
handler: { (action: UIAlertAction!) in
a = 2
// Call function here
}))
present(userAction, animated: true, completion: nil)
you can use semaphore to wait process until get signal.
Have a look at this tutorial https://medium.com/swiftly-swift/a-quick-look-at-semaphores-6b7b85233ddb, it's for GCD, but we can use it for main queue also.
Simply create let semaphore = DispatchSemaphore(value: 1) , then semaphore.wait() - wait until its get signal through semaphore.signal().
Have a look at tutorial link for more information.
Try doing it like this
let alertView = UIAlertController.init(title: "Enviado com sucesso!", message: "O seu bilhete foi enviado com sucesso", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { action in
//the Code you place here Will be called after user Select an action
}
alertView.addAction(OKAction)
self.present(alertView, animated: true, completion: nil)
Declare typealias on top of class like
import UIKit
typealias Request = ((_ value:String) -> ())
then your method :-
func showPopup( completion:#escaping Request) {
var a = 0 // default
let userAction = UIAlertController(title: "Select", message: "Select an action", preferredStyle: UIAlertControllerStyle.alert)
userAction.addAction(UIAlertAction(title: "action 1", style: .default, handler: { (action: UIAlertAction!) in
a = 1
let resp = Just.get("http://localhost/\(a)").text
completion(resp)
}))
userAction.addAction(UIAlertAction(title: "action 2", style: .cancel, handler: { (action: UIAlertAction!) in
a = 2
let resp = Just.get("http://localhost/\(a)").text
completion(resp)
}))
self.present(userAction, animated: true, completion: nil)
}
and call your method where you want like this:-
self.showPopup{ (value) in
print(value)
}

iOS 9, Swift 2.1 - Delete alert in vertical layout

I have a plain style alert that shows 2 buttons horizontally made with the following implementation and I'd like to know how I can make it like the attached image.
let alert = UIAlertController(title: "", message: "This item will be deleted", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil));
alert.addAction(UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {
alertAction in
self.deleteItem(sender)
}))
presentViewController(alert, animated: true, completion: nil);
Use this one :-
let alert = UIAlertController(title: "", message: "This item will be deleted", preferredStyle: .ActionSheet)
You can use the following for what u want to acheive
#IBAction func actionRecommend(sender: UIButton) {
let optionMenu = UIAlertController(title: nil, message: "Recommend Using", preferredStyle: .ActionSheet)
optionMenu.view.tintColor = primaryDarkColor
let deleteAction = UIAlertAction(title: "Facebook", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("File Facebook")
})
let saveAction = UIAlertAction(title: "Contacts", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("File toContacts")
// self.performSegueWithIdentifier("toContacts", sender: nil)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled")
})
optionMenu.addAction(deleteAction)
optionMenu.addAction(saveAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}

UIAlertController Swift

I have the following code
let alertController = UIAlertController(title: "error_title".localized, message: "error".localized, preferredStyle: .ActionSheet)
let retryAction = UIAlertAction(
title: "retry".localized,
style: .Default,
handler: {
(action:UIAlertAction!) in
self.fetch()
}
)
alertController.addAction(retryAction)
let cancelAction = UIAlertAction(
title: "cancel".localized,
style: .Default,
handler: {
(action:UIAlertAction!) in
self.navigationController!.popViewControllerAnimated(true)
}
)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
The dialog is shown ok but when I click a button it does not call the handler function. Any idea?
You can try this code.
let alertController = UIAlertController(title: "AlertCotrol", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ... Do something
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ... Do something
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ... Do something
}
For the internationalization where you have:
title: "retry".localized,
Try changing it to something like:
title: (NSLocalizedString("retry" , comment: "Retry something.") as String),
You may do the same for all the other strings that you want to internationalize, in the code you presented they are the strings you put ".localized" in front.
Of course you must have in your bundle the Localizable.strings file already set to the languages you want. If you need there is more about it at How to localize my app with Xcode 4?
Good luck.

How to present iOS UIActionSheet in Swift?

How can I present a UIActionSheet in Swift within an iOS app?
Here is my code for displaying a UIActionSheet:
#IBAction func downloadSheet(sender: AnyObject) {
let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)
let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
println("Saved")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
println("Deleted")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
println("Cancelled")
})
optionMenu.addAction(deleteAction)
optionMenu.addAction(saveAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
Updated for Swift 4/5
Works for iOS 11-14
Some of the other answers are okay but I ended up mixing and matching a few of them to rather come up with this :
#IBAction func showAlert(sender: AnyObject) {
let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))
alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
print("User click Edit button")
}))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
print("User click Delete button")
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
//uncomment for iPad Support
//alert.popoverPresentationController?.sourceView = self.view
self.present(alert, animated: true, completion: {
print("completion block")
})
}
Enjoy :)
Your Approach is fine, but you can add UIActionSheet with other way with ease.
You can add UIActionSheetDelegate in UIViewController` like
class ViewController: UIViewController ,UIActionSheetDelegate
Set you method like,
#IBAction func downloadSheet(sender: AnyObject)
{
let actionSheet = UIActionSheet(title: "Choose Option", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Save", "Delete")
actionSheet.showInView(self.view)
}
You can get your button index when it clicked like
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
println("\(buttonIndex)")
switch (buttonIndex){
case 0:
println("Cancel")
case 1:
println("Save")
case 2:
println("Delete")
default:
println("Default")
//Some code here..
}
}
Update 1: for iOS8+
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .ActionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default)
{ _ in
print("Save")
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default)
{ _ in
print("Delete")
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
UIActionSheet is deprecated in iOS 8.
I am using following:
// Create the AlertController
let actionSheetController = UIAlertController(title: "Please select", message: "How you would like to utilize the app?", preferredStyle: .ActionSheet)
// Create and add the Cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
// Create and add first option action
let takePictureAction = UIAlertAction(title: "Consumer", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_customer", sender: self)
}
actionSheetController.addAction(takePictureAction)
// Create and add a second option action
let choosePictureAction = UIAlertAction(title: "Service provider", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_provider", sender: self)
}
actionSheetController.addAction(choosePictureAction)
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = sender as UIView
// Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
Updated for Swift 3.x, Swift 4.x, Swift 5.x
// create an actionSheet
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// create an action
let firstAction: UIAlertAction = UIAlertAction(title: "First Action", style: .default) { action -> Void in
print("First Action pressed")
}
let secondAction: UIAlertAction = UIAlertAction(title: "Second Action", style: .default) { action -> Void in
print("Second Action pressed")
}
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }
// add actions
actionSheetController.addAction(firstAction)
actionSheetController.addAction(secondAction)
actionSheetController.addAction(cancelAction)
// present an actionSheet...
// present(actionSheetController, animated: true, completion: nil) // doesn't work for iPad
actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad
present(actionSheetController, animated: true) {
print("option menu presented")
}
Update for Swift 3:
// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
print("Save")
}
actionSheetController.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)
Generetic Action Sheet working for Swift 4, 4.2, 5
If you like a generic version that you can call from every ViewController and in every project try this one:
class Alerts {
static func showActionsheet(viewController: UIViewController, title: String, message: String, actions: [(String, UIAlertActionStyle)], completion: #escaping (_ index: Int) -> Void) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for (index, (title, style)) in actions.enumerated() {
let alertAction = UIAlertAction(title: title, style: style) { (_) in
completion(index)
}
alertViewController.addAction(alertAction)
}
// iPad Support
alertViewController.popoverPresentationController?.sourceView = viewController.view
viewController.present(alertViewController, animated: true, completion: nil)
}
}
Call like this in your ViewController.
var actions: [(String, UIAlertActionStyle)] = []
actions.append(("Action 1", UIAlertActionStyle.default))
actions.append(("Action 2", UIAlertActionStyle.destructive))
actions.append(("Action 3", UIAlertActionStyle.cancel))
//self = ViewController
Alerts.showActionsheet(viewController: self, title: "D_My ActionTitle", message: "General Message in Action Sheet", actions: actions) { (index) in
print("call action \(index)")
/*
results
call action 0
call action 1
call action 2
*/
}
Attention: Maybe you're wondering why I add Action 1/2/3 but got results like 0,1,2. In the line for (index, (title, style)) in actions.enumerated() I get the index of actions. Arrays always begin with the index 0. So the completion is 0,1,2.
If you like to set a enum, an id or another identifier I would recommend to hand over an object in parameter actions.
Action Sheet in iOS10 with Swift3.0. Follow this link.
#IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
2022 Swift 5
func yourActionSheet() -> UIAlertController {
let alert = UIAlertController(title: "Your title",
message: nil,
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Your action 1",
style: .default) { _ in
// onAction1()
})
alert.addAction(UIAlertAction(title: "Your action 2",
style: .default) { _ in
// onAction2()
})
alert.addAction(UIAlertAction(title: "Your cancel action",
style: .cancel) { _ in
// onCancel
})
return alert
}
SWIFT 4
WORKS ON IPHONE AND IPAD BOTH. ALSO ALLOWS ROTATION
LANDSCAPE
PORTRAIT
Code (tested)
let alert = UIAlertController()
let width: Int = Int(UIScreen.main.bounds.width - 100)
let viewAction = UIAlertAction(title: "View", style: .default , handler:{ (UIAlertAction)in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let orderDetailVC = storyboard.instantiateViewController(withIdentifier: "orderDetail") as! OrderDetailTableViewController
orderDetailVC.orderId = self.myDraftOrders[indexPath.row]["id"].intValue
self.navigationController?.pushViewController(orderDetailVC, animated: true)
})
viewAction.setValue(appGreenColor, forKey: "titleTextColor")
alert.addAction(viewAction)
let modifyAction = UIAlertAction(title: "Modify", style: .default, handler:{ (UIAlertAction)in
showAlert("Coming soon...")
})
modifyAction.setValue(appCyanColor, forKey: "titleTextColor")
alert.addAction(modifyAction)
let copyAction = UIAlertAction(title: "Copy", style: .default, handler:{ (UIAlertAction)in
self.copyOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue)
})
copyAction.setValue(appBlueColor, forKey: "titleTextColor")
alert.addAction(copyAction)
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
self.deleteOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue, indexPath: indexPath)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
let popover = alert.popoverPresentationController
popover?.delegate = self
let cellT = tableView.cellForRow(at: indexPath)
popover?.sourceView = cellT
popover?.sourceRect = CGRect(x: width, y: 25, width: 100, height: 50)
present(alert, animated: true)
Swift :
The sample code given below works both on iPhone and iPad.
guard let viewRect = sender as? UIView else {
return
}
let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
cameraSettingsAlert.modalPresentationStyle = .Popover
let photoResolutionAction = UIAlertAction(title: NSLocalizedString("Photo Resolution", comment: ""), style: .Default) { action in
}
let cameraOrientationAction = UIAlertAction(title: NSLocalizedString("Camera Orientation", comment: ""), style: .Default) { action in
}
let flashModeAction = UIAlertAction(title: NSLocalizedString("Flash Mode", comment: ""), style: .Default) { action in
}
let timeStampOnPhotoAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in
}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(cameraOrientationAction)
cameraSettingsAlert.addAction(flashModeAction)
cameraSettingsAlert.addAction(timeStampOnPhotoAction)
cameraSettingsAlert.addAction(photoResolutionAction)
if let presenter = cameraSettingsAlert.popoverPresentationController {
presenter.sourceView = viewRect;
presenter.sourceRect = viewRect.bounds;
}
presentViewController(cameraSettingsAlert, animated: true, completion: nil)
The Old Way: UIActionSheet
let actionSheet = UIActionSheet(title: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitles: "OK")
actionSheet.actionSheetStyle = .Default
actionSheet.showInView(self.view)
// MARK: UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: nil, message: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive) { (action) in
println(action)
}
alertController.addAction(destroyAction)
self.presentViewController(alertController, animated: true) {
// ...
}
Swift 3
For displaying UIAlertController from UIBarButtonItem on iPad
let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))
alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
print("User click Edit button")
}))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
print("User click Delete button")
}))
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
if let presenter = alert.popoverPresentationController {
presenter.barButtonItem = sender
}
self.present(alert, animated: true, completion: {
print("completion block")
})
swift4 (tested)
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
Code for adding alerts to actionsheet in swift4
*That means when we click actionsheet values(like edit/ delete..so on) it shows
an alert option that is set with Yes or No option*
class ViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)
action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
print("User click Approve button")
let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
print("User click Edit button")
let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
print("User click Delete button")
let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
print("User click cancel button")
let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
self.present(action_sheet1, animated: true, completion: {
print("completion block")
})
}
}
Useful to populate dynamic actions list, and listen to selected action:
var categories = ["Science", "History", "Industry", "Agriculture"]
var handlerSelectedCategory: ((Int) -> ())?
func prepareActions(for title: String, index: Int) -> UIAlertAction {
let alertAction = UIAlertAction(title: title, style: .default) { (action) in
self.handlerSelectedCategory?(index)
}
return alertAction
}
#objc func presentActions() {
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// add dymamic options
for (index, element) in self.categories.enumerated() {
optionMenu.addAction(prepareActions(for: element, index: index))
}
// cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
optionMenu.addAction(cancelAction)
handlerSelectedCategory = { index in
print(index, self.categories[index])
}
self.present(optionMenu, animated: true, completion: nil)
}
You can use following code for Alert and ActionSheet in Swift 4:
#IBAction func alert_act(_ sender: Any) {
do {
let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
#IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
action_sheet1.addAction(defaultAction)
action_sheet1.addAction(deleteAction)
action_sheet1.addAction(cancelAction)
self.present(action_sheet1, animated: true, completion: nil)
}
Swift 5+
Very Simple and Smooth way just call this function and Boommmmmm!!!!!!!
let IPAD = UIDevice.current.userInterfaceIdiom == .pad
//Mark:- Choose Image Method
func funcMyActionSheet() {
var myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
myActionSheet.view.tintColor = UIColor.black
let galleryAction = UIAlertAction(title: "Gallery".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.openGallary()
})
let cmaeraAction = UIAlertAction(title: "Camera".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.openCamera()
})
let cancelAction = UIAlertAction(title: "Cancel".localizableString(language: Defaults.selectedLanguageCode), style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
if IPAD {
//In iPad Change Rect to position Popover
myActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
}
myActionSheet.addAction(galleryAction)
myActionSheet.addAction(cmaeraAction)
myActionSheet.addAction(cancelAction)
print("Action Sheet call")
self.present(myActionSheet, animated: true, completion: nil)
}
You can use following code for open actionSheet in Swift:
let alert = UIAlertController(title: enter your title, message: "Enter your messgage. ", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:{ (UIAlertAction)in
print("User click Cancel button")
}))
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})

How to create UIActionSheet actions?

I know I have to set the delegate (I did so like this: class ShiftOverview: UITableViewController, UIActionSheetDelegate {...) but I'm still getting no response when I tap the buttons.
It doesn't look like you can set the delegate within the function with UIAlertController either...
#IBAction func takeShift(sender: AnyObject) {
let myActionSheet = UIAlertController (title: "Confirm", message: "Test message", preferredStyle: UIAlertControllerStyle.ActionSheet)
let actionOne = UIAlertAction (title: "Take Shift", style: .Default, handler: nil)
let actionTwo = UIAlertAction (title: "View ESA", style: .Default, handler: nil)
let actionCancel = UIAlertAction (title: "Cancel", style: .Cancel, handler: nil)
myActionSheet.addAction(actionOne)
myActionSheet.addAction(actionTwo)
myActionSheet.addAction(actionCancel)
self.presentViewController(myActionSheet, animated: true, completion: nil)
}
func actionSheet (myActionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
switch buttonIndex {
case 0:
println ("test0")
break
case 1:
println ("test1")
break
case 2:
println ("test2")
break
default:
println("nope")
}
}
Prior to iOS 8, UIAlertViews and UIActionSheets were separate controls. In iOS 8 however, a new class, UIAlertController, combines both these controls into a single, easy to use class.
Rather than using the delegation pattern like these controls used to, you now pass a closure to be called. The places where you have handler equal to nil is where you put your code.
This is likely added because Swift treats closures as first-class citizens, while Objective C did not as much (with blocks).
It should be:
#IBAction func takeShift(sender: AnyObject) {
let myActionSheet = UIAlertController (title: "Confirm", message: "Test message", preferredStyle: UIAlertControllerStyle.ActionSheet)
let actionOne = UIAlertAction (title: "Take Shift", style: .Default, handler: { (action) in
println("test0")
})
let actionTwo = UIAlertAction (title: "View ESA", style: .Default, handler: { (action) in
println("test1")
})
let actionCancel = UIAlertAction (title: "Cancel", style: .Cancel, handler: { (action) in
println("test2")
})
myActionSheet.addAction(actionOne)
myActionSheet.addAction(actionTwo)
myActionSheet.addAction(actionCancel)
self.presentViewController(myActionSheet, animated: true, completion: nil)
}
Read more about this in NSHipster's article on UIAlertControllers or in its documentation.
Instead of passing nil to your handler, you can write the action you want to perform. You don't need the delegate method anymore.
let actionOne = UIAlertAction (title: "Take Shift", style: .Default){ (action) -> Void in
println ("Take Shift")
};
let actionTwo = UIAlertAction (title: "View ESA", style: .Default){ (action) -> Void in
println ("View ESA")
};
let actionCancel = UIAlertAction (title: "Cancel", style: .Cancel){ (action) -> Void in
println ("Cancel")
};
You may like to see this also:
func AlertViewWithActionsheet () {
let alert = UIAlertController(title: "Alert with actionsheet", message: "Alert with actionsheet", preferredStyle: UIAlertControllerStyle.ActionSheet);
let dismissHandler = {
(action: UIAlertAction!) in
// This is an action event - called when you press OK button.
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
// add action
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: dismissHandler))
presentViewController(alert, animated: true) { () -> Void in
}
}

Resources