Last active
June 30, 2019 14:24
-
-
Save flannerykj/cab913c979315ae2f37d343af8996879 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class PlaygroundViewController: UIViewController { | |
let firstViewController = UIViewController() | |
let secondViewController = UIViewController() | |
let thirdViewController = UIViewController() | |
lazy var viewControllersToAdd = [firstViewController, secondViewController, thirdViewController] | |
let heightOfView: CGFloat = 300 | |
let viewOverlap: CGFloat = 200 | |
let stackView = UIStackView() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = UIColor.white | |
firstViewController.view.backgroundColor = .red | |
secondViewController.view.backgroundColor = .blue | |
thirdViewController.view.backgroundColor = .green | |
stackView.translatesAutoresizingMaskIntoConstraints = false | |
stackView.axis = .vertical | |
stackView.spacing = -viewOverlap | |
viewControllersToAdd.forEach { (controller: UIViewController) in | |
if let childView = controller.view { | |
stackView.addArrangedSubview(childView) | |
NSLayoutConstraint.activate([ | |
childView.heightAnchor.constraint(equalToConstant: heightOfView), | |
childView.widthAnchor.constraint(equalTo: stackView.widthAnchor) | |
]) | |
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapChildView(sender:))) | |
childView.addGestureRecognizer(gestureRecognizer) | |
childView.isUserInteractionEnabled = true | |
} | |
addChild(controller) | |
controller.didMove(toParent: self) | |
} | |
view.addSubview(stackView) | |
NSLayoutConstraint.activate([ | |
stackView.rightAnchor.constraint(equalTo: view.rightAnchor), | |
stackView.leftAnchor.constraint(equalTo: view.leftAnchor), | |
stackView.topAnchor.constraint(equalTo: view.topAnchor), | |
]) | |
} | |
@objc func didTapChildView(sender: UITapGestureRecognizer) { | |
if let targetView = sender.view { | |
UIView.animate(withDuration: 0.3, animations: { | |
let currentSpacing = self.stackView.customSpacing(after: targetView) | |
if currentSpacing == 0 { | |
// targetView is already expanded, collapse it | |
self.stackView.setCustomSpacing(-self.viewOverlap, after: targetView) | |
} else { | |
// expand view | |
self.stackView.setCustomSpacing(0, after: targetView) | |
} | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment