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: https://trailheadtechnology.com/gradient-backgrounds-in-xamarin-ios/

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:

Manage Your Windows Applications With Winget

Winget, Microsoft’s native package manager for Windows 10 (version 1709 and later) and Windows 11, offers a streamlined CLI for efficient application management. This blog post introduces Winget’s installation and basic commands for installing, updating, and removing software. It highlights the tool’s ability to manage non-Winget-installed apps and explores curated package lists for batch installations. The post also recommends top Winget packages, noting some may require a paid subscription.

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! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

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

Ready to come with us? 

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 contact form. 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.