Expandable UITableView with Xamarin iOS

Expandable UITableViewCells with variable height, beautiful animations and no 3rd party libraries – all with just a few lines of code. Interested? Let me show you how I got all of these.

Let’s start by taking a look at the final result:

There are four animations here to get this effect done. When users tap on an item, the UITableView changes the height of the cell to show the hidden content. A little arrow icon is rotated to indicate that the cell is expanded. And to make it look more natural, the background color of the cell is changed and the hidden content fades-in.

Cell animation

First, we will let the UITableView know that our cells are of variable height.

TableViewItems.RowHeight = UITableView.AutomaticDimension;
TableViewItems.EstimatedRowHeight = 60;

Now, the most interesting part — the cell itself.

I’m using a little trick with constraints here to get the animation done with no effort. Notice that there are two unbroken chains of constraints here:

  1. Superview — UIImageView — (1)— Superview
  2. Superview — UIImageView — (2)— UILabel — Superview

The priority of Constraint 1 (UIImageView — Superview) is set to 999 (we don’t want to use 1000 here because it’ll be not possible to change it later to a lower value).

The priority of Constraint 2 (UIImageView — UILabelView) is set to 750.

As long as Constraint 1 has a higher priority than Constraint 2 the cell is collapsed. As soon as we change the priority of Constraint 1 to a lower value, the cell will expand.

Since the hidden content might be of a variable length. There are a few properties to set on UILabel as well:


 

Now let’s handle the row selected event. We need just three lines of code to expand/collapse a cell.

tableView.BeginUpdates();
cell.Constraint.Priority = cell.Expanded ? 250 : 999;
tableView.EndUpdates();

Here we’re changing the priority of Constraint 1 from the above to a lower value to expand the cell (or back to the higher value to collapse it). UITableView takes care of everything else, including the animation. Not bad, right?


 

UIImageView Rotation

It’s really simple to rotate an image using built-in animations of UIKit:

var transformation = expanded ? CoreGraphics.CGAffineTransform.MakeRotation((nfloat)(-0.99999 * Math.PI)) : CoreGraphics.CGAffineTransform.MakeIdentity();
Animate(0.4, () => { ImageViewArrow.Transform = transformation; });

Note a small hack here. I multiple Math.PI by -0.99999 to make it rotate counterclockwise.

Background Color

Plain UIKit animation without any hacks:

var backgroundColor = expanded ? UIColor.FromRGBA(0, 0, 0, 0.2f) : UIColor.Clear;
Animate(0.4, () => { BackgroundColor = backgroundColor; });

Fade-in effect

Unfortunately, it’s not possible to use the Animate function to change a text color. So I’m using the Transition function here.

var labelColor = expanded ? UIColor.White : UIColor.Clear;
UIView.Transition(LabelDetails, 0.4, UIViewAnimationOptions.TransitionCrossDissolve, () =>
{
    LabelDetails.TextColor = labelColor;
}, null);

Cell Recycling

The final thing that we need to take care of is the cell recycling. Each time when a user expands/collapses a cell, we need to save the state somewhere and make sure that cells are initialized according to that state.

Here is my cell class:

[Register (“FaqItemCell”)]
public partial class FaqItemCell&nbsp;: ReactiveTableViewCell<FaqItem>
{
    public static readonly NSString Key = new NSString(“FaqItemCellKey”);
    public static readonly float Height = (float)UITableView.AutomaticDimension;
    public bool Expanded
    {
        get => ViewModel.Expanded;
        set => ViewModel.Expanded = value;
    }
    public FaqItemCell(IntPtr handle)&nbsp;: base(handle)
    {
        this.WhenActivated(d =>
        {
            this.OneWayBind(ViewModel, vm => vm.Title, v => v.LabelTitle.Text).DisposeWith(d);
            this.OneWayBind(ViewModel, vm => vm.Details, v => v.LabelDetails.Text).DisposeWith(d);
        });
    }
    public void Initialize()
    {
        SetState(Expanded, false);
    }
    public void SetState(bool expanded, bool animated)
    {
        var backgroundColor = expanded&nbsp;? UIColor.FromRGBA(0, 0, 0, 0.2f)&nbsp;: UIColor.Clear;
        var labelColor = expanded&nbsp;? UIColor.White&nbsp;: UIColor.Clear;
        var transformation = expanded&nbsp;? CoreGraphics.CGAffineTransform.MakeRotation((nfloat)(-0.99999 * Math.PI))&nbsp;: CoreGraphics.CGAffineTransform.MakeIdentity();
        ConstraintBottom.Priority = expanded&nbsp;? 250&nbsp;: 999;
        if (animated)
        {
            Animate(0.4, () =>
            {
                BackgroundColor = backgroundColor;
                ImageViewArrow.Transform = transformation;
            });
            UIView.Transition(LabelDetails, 0.4, UIViewAnimationOptions.TransitionCrossDissolve, () =>
            {
                LabelDetails.TextColor = labelColor;
            }, null);
        }
        else
        {
            BackgroundColor = backgroundColor;
            ImageViewArrow.Transform = transformation;
            LabelDetails.TextColor = labelColor;
        }
    }
}

 

I’m using a view model to persist the cell state. Each time when a cell is initialized I apply the state without animation. When a user interacts with the table, I reuse the same method to expand/collapse the cell with animation.

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
    base.RowSelected(tableView, indexPath);
    var cell = tableView.CellAt(indexPath) as FaqItemCell;
    cell.Expanded = !cell.Expanded;
    tableView.BeginUpdates();
    cell.SetState(cell.Expanded, true);
    tableView.EndUpdates();
}

I hope you’ll find it useful! By the way, here is how I create awesome gradient backgrounds: /gradient-backgrounds-in-xamarin-ios/

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Xamarin.Forms Fancy Animations

Xamarin.Forms includes its own animation infrastructure that allows for easy creation of simple animations, while also being versatile enough to create complex animations. Let’s take a look how we can reproduce some popular animations with

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.