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:
- Superview — UIImageView — (1)— Superview
- 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 : 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) : 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 ? UIColor.FromRGBA(0, 0, 0, 0.2f) : UIColor.Clear; var labelColor = expanded ? UIColor.White : UIColor.Clear; var transformation = expanded ? CoreGraphics.CGAffineTransform.MakeRotation((nfloat)(-0.99999 * Math.PI)) : CoreGraphics.CGAffineTransform.MakeIdentity(); ConstraintBottom.Priority = expanded ? 250 : 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/