ActionSheet Example in Swift

In this Swift video tutorial I am going to share with you how to use UIAlertController to create an ActionSheet with three different buttons styles:

  • Default style for Send now button,
  • Destructive style for Delete button
  • Cancel style for Cancel button

For each button option I will also create an action handler which we can use to run some code when user taps on selected button.

Below is the code example you can copy, paste and run in your Xcode and a video tutorial where I walk you through each line of this code example.

Use UIAlertController to Create an ActionSheet. Swift Code Example.

import UIKit

class ViewController: UIViewController  {
  
  override func viewDidLoad() {
      super.viewDidLoad()
  }
  
  override func viewWillAppear(animated: Bool) {
      super.viewWillAppear(animated)
      
      
      let alertController = UIAlertController(title: "Action Sheet", message: "What would you like to do?", preferredStyle: .ActionSheet)
      
      let sendButton = UIAlertAction(title: "Send now", style: .Default, handler: { (action) -> Void in
          print("Ok button tapped")
      })
      
      let  deleteButton = UIAlertAction(title: "Delete forever", style: .Destructive, handler: { (action) -> Void in
          print("Delete button tapped")
      })
      
      let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
          print("Cancel button tapped")
      })
      
      
      alertController.addAction(sendButton)
      alertController.addAction(deleteButton)
      alertController.addAction(cancelButton)
      
      self.navigationController!.presentViewController(alertController, animated: true, completion: nil)
      
  }
}

Create an ActionSheet in Swift. Video Tutorial.

You can find more Swift Code Examples on this page : http://swiftdeveloperblog.com/code-examples/

I hope this blog post was helpful for you!

Happy learning!