Let's say you have a table view with some cells showing a list of crew members. It'd be great if when the user taps a cell, it would โexpandโ to reveal some actions that can be performed on that crew member. Let's dive in.
Setup View Hierarchy
As you can see, we lean on UIStackView pretty heavily. The constraint shown here is the one we'll be animating.
Animate the Constraint
In our cell's setSelected(animated:)
function, we animate the constraint just like we covered back in Bite #9. After the animation's done, we hide/show the toolbar. This triggers the top-level stack view to recalculate it's height.
let constant: CGFloat = selected ? 30.0 : 0.0
let options = [.AllowUserInteraction, .BeginFromCurrentState]
UIView.animateWithDuration(0.3, delay: 0.0, options: options, animations: {
self.toolbarStackViewHeightConstraint.constant = constant
self.layoutIfNeeded()
}, completion: { completed in
self.toolbarStackView.hidden = !selected
})
Final Product
Our view controller takes care of resizing our cells by updating the 'expanded' state of each crew member when the selection changes and a pair of calls to tableView.beginUpdates
/endUpdates
inside the tableView:didSelectRowAtIndexPath:
and tableView:didDeselectRowAtIndexPath:
.
Download the complete working project here: j.mp/bite050