Skip to content

Instantly share code, notes, and snippets.

@karigrooms
Created February 23, 2021 18:46
Show Gist options
  • Save karigrooms/8db20f12a7d7078e377e1600f87e4ab2 to your computer and use it in GitHub Desktop.
Save karigrooms/8db20f12a7d7078e377e1600f87e4ab2 to your computer and use it in GitHub Desktop.
Blog post: SwiftUI with UICollectionView - 2. Embed SwiftUI Card in UICollectionViewCell
import SwiftUI
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
static var reuseIdentifier = "MyCollectionViewCell"
lazy var host: UIHostingController = {
return UIHostingController(rootView: Card())
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
host.view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(host.view)
NSLayoutConstraint.activate([
host.view.topAnchor.constraint(equalTo: contentView.topAnchor),
host.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
host.view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
host.view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment