Skip to content

Instantly share code, notes, and snippets.

@danurna
Created July 26, 2022 09:25
Show Gist options
  • Save danurna/0d438155fa6943c9ae71c015325bb40d to your computer and use it in GitHub Desktop.
Save danurna/0d438155fa6943c9ae71c015325bb40d to your computer and use it in GitHub Desktop.
CatsUIView Sample
class CatsUIView: UIView {
private var catsView: CatsView?
private var hostingViewController: UIViewController?
...
override func didMoveToSuperview() {
super.didMoveToSuperview()
guard hostingViewController == nil else { return }
let catsView = CatsView(.init(onSizeChange: { [weak self] in
self?.invalidateIntrinsicContentSize() // #5
}))
self.catsView = catsView
hostingViewController = UIHostingController(rootView: catsView) // #1
guard let embeddedCatsView = hostingViewController?.view else { return }
// Pin view to edges of hosting view
embeddedCatsView.translatesAutoresizingMaskIntoConstraints = false
addSubview(embeddedCatsView) // #2
[
embeddedCatsView.topAnchor.constraint(equalTo: topAnchor),
embeddedCatsView.bottomAnchor.constraint(equalTo: bottomAnchor),
embeddedCatsView.leadingAnchor.constraint(equalTo: leadingAnchor),
embeddedCatsView.trailingAnchor.constraint(equalTo: trailingAnchor)
].forEach { $0.isActive = true } // #3
...
}
override var intrinsicContentSize: CGSize {
return hostingViewController?.view.intrinsicContentSize ?? .zero // #4
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment