Skip to content

Instantly share code, notes, and snippets.

@karambirov
Created August 23, 2022 07:51
Show Gist options
  • Save karambirov/706ae87c43f66ccf781de55b304dcf59 to your computer and use it in GitHub Desktop.
Save karambirov/706ae87c43f66ccf781de55b304dcf59 to your computer and use it in GitHub Desktop.
Wrappers for UICollectionReusableView and UICollectionViewCell which allow to use SwiftUI views in UIKit UICollectionView
import SwiftUI
public class HostingCollectionReusableView<Content: View>: UICollectionReusableView {
private let hostingController = UIHostingController<Content?>(rootView: nil, ignoreSafeArea: true)
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(with view: Content) {
hostingController.rootView = view
hostingController.view.backgroundColor = .clear
hostingController.view.invalidateIntrinsicContentSize()
}
private func setup() {
addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: trailingAnchor),
hostingController.view.topAnchor.constraint(equalTo: topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
import SwiftUI
public class HostingCollectionViewCell<Content: View>: UICollectionViewCell {
private let hostingController = UIHostingController<Content?>(rootView: nil, ignoreSafeArea: true)
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(with view: Content) {
hostingController.rootView = view
hostingController.view.backgroundColor = .clear
hostingController.view.invalidateIntrinsicContentSize()
}
private func setup() {
contentView.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
hostingController.view.topAnchor.constraint(equalTo: contentView.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment