ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

 iOS - How to make TableView Actions in Swift

Updated on October 12, 2017

Hi there,

here you'll learn how to create a UITableView in Swift and setup a couple of nice UITableViewActions that will show up with a left swipe on a cell and allow you to do additional functions in your app.

Let's start by creating a new XCode project, Single View Application, name it as you wish and hit the Next blue button.

Select Single View Application
Select Single View Application | Source
Name your Xcode project as you wish
Name your Xcode project as you wish | Source

Now you have to search for TableView in the Object library panel on the bottom-right side of the Xcode window and drag the Table View into your Controller in the Storyboard. That screen should be attached to ViewController.swift so you'll be ready to start coding in a minite without having to create a new .swift file.

Adjust the Table View layout into the controller as you wish, we usually do not use Auto Layout because it messes up things while switching from small iPhone devices to bigger ones like iPad or the new iPad Pro. So we like to disable such auto layout option by the File Inspector panel: select the yellow icon on the Controller, unmark "User Auto Layout" option and click "Disable Size Classes" button on the popup that will show up, as shown below:

Disable Auto Layout and Size Classes
Disable Auto Layout and Size Classes

Let's go back to our TableView, we have to attach its Delegate and Datasource options to the Controller. You may do that by code but there's an easier way to do that. Right-click on your mouse, hold that right button and drag the pointer to the yellow icon of the View Controller and release the button. You'll see a small black popup with 2 options:

  • dataSource
  • delegate

Click on dataSource and repeat the steps above to click on delegate too.

Attach dataSource and delegate to your TableView
Attach dataSource and delegate to your TableView

Connect your TableView to the VideController.swift. In order for you to do that you have to split your Xcode window in 2 parts by clicking on the 2-circle icon on the right-top corner of Xcode, that's the Assistant Editor and it will show the ViewController.swift editor on the right side and the Storybard on the left side.

You can now right-click on the TableView, hold the mouse button and drag the pointer underneath the class declatarion. Hold up the finger from the right mouse button and name your TableView Outlet as myTableView.

Attach the TableView to your .swift file
Attach the TableView to your .swift file

You're done with Storyboard design, now let's code a bit.

You first have to add the UITableViewDelegate and UITableViewDataSource delegates to your class, so edit it as follows:

class ViewController: UIViewController,

It's time to create an Array of some elements for the TableView to show 3 rows after you'll run the app, so let's make it and call it myCells:

let myCells = ["Swipe me left!", "Swipe me left!", "Swipe me left!", ]

Place that Array just below the myTableView Outlet declaration.

Now let's add all the necessary TableView's delegate and datasource methods right below the closure of viewDidLoad(). Check the following code, we'll explain it later:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myCells.count
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        cell.textLabel?.text = myCells[indexPath.row]
return cell

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 60

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    // ACTION 1
    let action1 = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        // Remove the selected cell
    // ACTION 2
    let action2 = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Action 2" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        UIAlertView(title: "TableView Actions", message: "You've tapped Action 2!", delegate: nil, cancelButtonTitle: "OK").show()
    // Set image on the action 1
    action1.backgroundColor = UIColor(patternImage: UIImage(named: "actionImage")!)
    // Set background color on the action 2
    action2.backgroundColor = UIColor.blueColor()
// Lastly, return all the created Actions
return [action1, action2]

• Line 7: here we returned the amount of rows that your TableView should show, accordingly to the amount of items in the myCell Array.

• Line 13: Set the text of the cell's textLabel based on the index of the above Array. Keep in mind that Arrays are 0-indexed, which means that the first item of an array is at position 0, the second one on position 1 and so on. The TableView cells are also 0-indexed so the first cell's row is 0 (so indexPath.row = 0).

• Line 19: Set the height of all the cells, we chose 60 pixels because then the trash icon of one of our Actions will better fit the cell's height.

• Line 28: that's the instance of our first TableView Action, where we can assign a title to it. Anyway, this Action will show an image so you can leave its title sting empty, as we did.

Inside that block we've placed 2 lines of code that will remove the selected cell if you tap on the trash icon.

self.myCells.removeAtIndex(indexPath.row) will remove the selected cell.

self.myTableView.reloadData() will reload the TableView's in order to display the left cells.

• Line 41: Inside the second Action's block method we've initialized a UIAlertView that will show a simple title and message if you'll tap the blue Action 2 button.

• Line 47: This instance will set an image for the first Action button. Because of Cell's inner layout we had to make a png image with the size of 132x360px and placing the red button a little bit down from the top of the canvas top (see preview below). Please note that such image size is for iPhone 6 plus, so into Assets.xcassets folder in XCode you will have to drag that image into the 3x box, then you'll have to resize it to 88x240px and again to 44x120px, they will respectively be the 2x and 1x images (for older iPhones and non-retina iPads).

• Line 49: This short instance will instead set a simple background color to the second Action, and so you'll be able to see its title.

Last line will just set the created Actions into an array and display them after a left-swipe on a cell.

Click thumbnail to view full-size

You're done, bow run the app on the iOS Simulator or your real device, swipe on a cell and tap the red button with a trash icon to remove a cell, or the Action 2 blue button to show an AlertView.

You've just learned how to create Actions for TableView cells and assign them an icon instead of just showing its plain title.

Thanks for reading, don't forget to check out our other tutorials!


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)