Created
July 26, 2022 09:25
-
-
Save danurna/0d438155fa6943c9ae71c015325bb40d to your computer and use it in GitHub Desktop.
CatsUIView Sample
This file contains hidden or 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
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