Expandable view in iOS
If you have also wondered like me how to create those nice expandable views then I have found one way of achieving that.
I have two views First View and Second View (expandable view). First view will have a constant height of 60 (in my case) then for the second view we have to do following things:
- Give a height constraint of 0.
- Add bottom constraint with priority of 750 (default hight).
3. Now add some content in your second view, for simplicity I have added a stack view with 4 labels in it.
Now, we will write our ViewController.swift. I will break it down to make it more understandable.
@IBOutlet var firstView: UIView!@IBOutlet var secondView: UIView!@IBOutlet var mainHeightConstraint: NSLayoutConstraint!@IBOutlet var showMoreButton: UIButton!
First two outlets are from first and second view. Third outlet `mainHeightConstraint` is connected with the height constraint of the second view. Fourth one represents the button that starts this collapsed and expanded view behavior.
private var shouldCollapse = falsevar buttonTitle: String {return shouldCollapse ? "Show Less" : "Show More"}
This part of the code is used to store the state of the expanded and collapsed state of the button as well as to compute the string for the button in those states.
@IBAction func buttonTap(_ sender: Any) { if shouldCollapse { animateView(isCollapse: false, buttonText: buttonTitle, heighConstraint: 0) } else { animateView(isCollapse: true, buttonText: buttonTitle, heighConstraint: 100) }}
This part is used to call `animateView` function that animates the collapsing and expanding of the second view. In this function we are setting the height constraint to 100 when we want the second view to be expanded and setting it’s height to 0 when we want it to be collapsed.
private func animateView(isCollapse: Bool,buttonText: String,heighConstraint: Double) { shouldCollapse = isCollapse mainHeightConstraint.constant = CGFloat(heighConstraint) showMoreButton.setTitle(buttonTitle, for: .normal) UIView.animate(withDuration: 1) { self.view.layoutIfNeeded() }}
Last part is where height constraint actually gets set based on the state of the button.
If you want to see the entire code you can checkout this GitHub repo (https://github.com/singh88/ExpandableViewiOS)