UIActionSheet crashes on iPad swift - ios

I have the following button action in a toolbar:
#IBAction func share(sender: AnyObject) {
let modifiedURL1 = "http://www.declassifiedandratified.com/search.html?q=\(self.searchBar.text)"
let modifiedURL = modifiedURL1.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil)
let alert = UIAlertController(title: "Share", message: "Share your findings", preferredStyle: UIAlertControllerStyle.ActionSheet)
let twBtn = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default) { (alert) -> Void in
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){
var twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterSheet.setInitialText("Look what I found on Declassified and Ratified: \(modifiedURL)")
self.presentViewController(twitterSheet, animated: true, completion: nil)
} else {
var alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
let fbBtn = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default) { (alert) -> Void in
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){
var facebookSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
facebookSheet.setInitialText("Look what I found on Declassified and Ratified: \(modifiedURL)")
self.presentViewController(facebookSheet, animated: true, completion: nil)
} else {
var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
let safariBtn = UIAlertAction(title: "Open in Safari", style: UIAlertActionStyle.Default) { (alert) -> Void in
let URL = NSURL(string: modifiedURL)
UIApplication.sharedApplication().openURL(URL!)
}
let cancelButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (alert) -> Void in
println("Cancel Pressed")
}
let textBtn = UIAlertAction(title: "Message", style: UIAlertActionStyle.Default) { (alert) -> Void in
if (MFMessageComposeViewController.canSendText()) {
let controller = MFMessageComposeViewController()
controller.body = "Look what I found on Declassified and Ratified: \(modifiedURL)"
controller.messageComposeDelegate = self
self.presentViewController(controller, animated: true, completion: nil)
}
}
alert.addAction(twBtn)
alert.addAction(fbBtn)
alert.addAction(safariBtn)
alert.addAction(textBtn)
alert.addAction(cancelButton)
self.presentViewController(alert, animated: true, completion: nil)
}
However, this code crashes when called on an iPad with a sigbart crash (that is all I can see in the console). I see this is a common problem but the other solutions have not worked for me. I even set the version to the latest iOS and that didn't fix it. Can someone explain?

On an iPad, an action sheet is a popover. Therefore you must give its UIPopoverPresentationController a sourceView and sourceRect, or barButtonItem, so that it has something to attach its arrow to.

Related

Cancel style button not working in actionsheet of Ipad

I am trying to implement actionsheet in ipad with the help of popoverPresentationController.everything is working fine but i am facing one problem that Cancel
style button is not coming in the actionsheet.
here is my code for refernece
#IBAction func logoutAction(_ sender: UIButton) {
let alertController = UIAlertController(title: "", message: "do you want to logout", preferredStyle: .actionSheet)
let yesAction = UIAlertAction(title: "Logout", style: .destructive, handler: { (action) -> Void in
Singleton.sharedInstance.logoutButtonAction()
logEvent(label: "user_log_out")
})
let noAction = UIAlertAction(title: "cancel", style: .cancel, handler: { (action) -> Void in
self?.dismiss(animated: true, completion: nil)
})
alertController.addAction(yesAction)
alertController.addAction(noAction)
alertController.popoverPresentationController?.sourceView = self?.view
alertController.popoverPresentationController?.sourceRect = sender.frame
/* if let presenter = alertController.popoverPresentationController {
presenter.sourceView = self!.logoutButton
presenter.sourceRect = self!.logoutButton.bounds
}*/
self?.present(alertController, animated: true, completion: nil)
})
}
```

ViewController reloads on presenting alert controller swift

I am working on project. i have added a simple alertController on clicking signup button. when i click on the button my viewcontroller reloads and then it shows that alertController. It is happening on iOS 13 and swift 5 or above
let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
})
alert.addAction(cancel)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true)
})
i resolved my problem by these lines of code
func alert(message: String, title: String = "") {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default) { (action) in
print("Action")
}
alertController.addAction(alertAction)
(UIApplication.shared.delegate as! AppDelegate).alertWindow.isHidden = true
self.presentViewController(alertController: alertController)
// self.present(alertController, animated: true, completion: nil)
}
func presentViewController(alertController: UIAlertController, completion: (() -> Void)? = nil) {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
DispatchQueue.main.async {
topController.present(alertController, animated: true, completion: completion)
}
}
}

How can I pass a controller to a function

Hello I have a utility class in which I have declared AlertViewFunction like this
func displayAlertMessage(userMessage: String,//controller){
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
}
The problem is I can't use self here
self.presentViewController(myAlert, animated: true, completion: nil)
I want to pass a controller to this function so I can use like this
controller.presentViewController(myAlert, animated: true, completion: nil)
How Can I pass a controller from any ViewController. Lets say If I am in LoginViewController
Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED,//controller)
Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED, controller: self)
and
func displayAlertMessage(userMessage: String, controller: UIViewController)
{
controller?.presentViewController(myAlert, animated: true, completion: nil)
}
pass in the view controller as an argument to the function.
func displayAlertMessage(controller: UIViewController, title: String, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(okAction)
controller.presentViewController(alert, animated: false, completion: nil)
}
Alternatively you can even return the alert to the caller of the function for further customization by saying:
func displayAlertMessage(title: String, message: String?) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(okAction)
return alert
}
class controller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alert = displayAlertMessage("title", message: nil)
presentViewController(alert, animated: true, completion: nil)
}
}

Display an alert of reachability status

I'm using Reachability of ashleymills: https://github.com/ashleymills/Reachability.swift/releases
In Xcode 7, I wrote a function to display an alert of reachability status.
However, the alert never shows up.
Here is my code:
let reachability = Reachability.reachabilityForInternetConnection()
reachability!.whenReachable = { reachability in
if reachability.isReachableViaWiFi() {
let alertController = UIAlertController(title: "Alert", message: "Reachable via WiFi", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
else {
let alertController = UIAlertController(title: "Alert", message: "Reachable via Cellular", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
reachability!.whenUnreachable = { reachability in
let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
reachability!.startNotifier()
Please replace your code with this and it should work, there might be a bug in Reachability after swift 1.2, so here I'm just checking if its reachable or not and i think its enough.
In my opinion you don't have to check if its the wifi or cellular, The reason behind the alert isn't showing because its not entering the blocks to show the alert :
let useClosures = false
class ViewController: UIViewController {
let reachability = Reachability.reachabilityForInternetConnection()
override func viewDidLoad() {
super.viewDidLoad()
if (useClosures) {
reachability?.whenReachable = { reachability in
print("Reachable")
}
reachability?.whenUnreachable = { reachability in
print("Unreachable")
}
} else {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
}
reachability?.startNotifier()
// Initial reachability check when the app starts
if let reachability = reachability {
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachable() {
let alertController = UIAlertController(title: "Alert", message: "Reachable", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
}
deinit {
reachability?.stopNotifier()
if (!useClosures) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
}
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
// Initial reachability check while surfing in the app
if reachability.isReachable() {
let alertController = UIAlertController(title: "Alert", message: "Reachable", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
Note : You said you have webView in your app, remember that you have to refresh or update when its reachable.

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")
})

Resources