Skip to content

EpoxyBars

Tyler Hedrick edited this page Jan 14, 2021 · 5 revisions

EpoxyBars is a declarative API to add fixed top and bottom bars to your UIViewController. Adding these bars is simple:

final class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    topBarInstaller.setBars(topBars, animated: false)
    bottomBarInstaller.setBars(bottomBars, animated: false)
    topBarInstaller.install()
    bottomBarInstaller.install()
  }

  private lazy var topBarInstaller = TopBarInstaller(viewController: self)
  private lazy var bottomBarInstaller = BottomBarInstaller(viewController: self)

  private var topBars: [BarModeling] {
    [
      // Instantiate BarModels for the top bars here
    ]
  }

  private var bottomBars: [BarModeling] {
    [
      // Instantiate BarModels for the bottom bars here
    ]
  }

}

Each bar is represented by a BarModel which follows the same conventions as all of the view models in Epoxy. You can create a BarModel for any UIView:

private var bottomBars: [BarModeling] {
  [
    BarModel<UIButton, String>(
      content: "Buy Now",
      makeView: {
        let button = UIButton(type: .system)
        button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title2)
        return button
      },
      configureView: { context in
        context.view.setTitle(context.content, for: .normal)
      })
  ]
}

Calling setBars(_ bars: [BarModeling], animated: Bool) will perform a diff between the given models and the current installed models. The bar installer will then update the UI to render the new set of bars and optionally animate the change.

Under the hood the bar installer will put each view into a container and render that container in the provided UIViewController's view. It will update content insets accordingly and respect the safeAreaInsets as well.