Part 5 – Working with Row Actions

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

The UITableViewRowAction class is used to define an action that will take place when the user swipes left horizontally on a row in a UITableView. For example, when editing a table, swiping left on a row displays a Delete button by default. By attaching multiple instances of the UITableViewRowAction class to a UITableView, multiple custom actions can be defined, each with its own text, formatting and behavior.

Adding a new Row Action

To define one or more custom row actions for a UITableView, you will need to create an instance of the UITableViewDelegate class and override the EditActionsForRow method. For example:

using System;
using System.Collections.Generic;
using System.IO;
using Foundation;
using UIKit;

namespace BasicTable
{
    public class TableDelegate : UITableViewDelegate
    {
        #region Constructors
        public TableDelegate ()
        {
        }

        public TableDelegate (IntPtr handle) : base (handle)
        {
        }

        public TableDelegate (NSObjectFlag t) : base (t)
        {
        }

        #endregion

        #region Override Methods
        public override UITableViewRowAction[] EditActionsForRow (UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewRowAction hiButton = UITableViewRowAction.Create (
                UITableViewRowActionStyle.Default,
                "Hi",
                delegate {
                    Console.WriteLine ("Hello World!");
                });
            return new UITableViewRowAction[] { hiButton };
        }
        #endregion
    }
}

The static UITableViewRowAction.Create method is used to create a new UITableViewRowAction that will display a Hi button when the user swipes left horizontally on a row in the table. Later a new instance of the TableDelegate is created and attached to the UITableView. For example:

TableDelegate tableDelegate;
...

// Replace the standard delete button with a "Hi" button
tableDelegate = new TableDelegate ();
table.Delegate = tableDelegate;

When the above code is run and the user swipes left on a table row, the Hi button will be displayed instead of the Delete button that is displayed by default:

If the user taps the Hi button, Hello World! will be written out to the console in Xamarin Studio or Visual Studio when the application is run in the debug mode.

There is a community sample available that supports swiping both left and right; behavior which is exhibited in Apple's Mail app but which is not available in UIKIt by default.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.