ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

 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,
UITableViewDelegate,
UITableViewDataSource
{

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:

// MARK: - TABLEVIEW DELEGATES
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
}  
    

// MARK: - EDIT ACTIONS ON SWIPE ON A CELL
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
        self.myCells.removeAtIndex(indexPath.row)
        self.myTableView.reloadData()
    })
    
    
    // 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!

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.