Skip to content

Instantly share code, notes, and snippets.

@hira22
Created July 29, 2021 05:55
Show Gist options
  • Save hira22/bac2aa24461b71a80d76022f58fd9273 to your computer and use it in GitHub Desktop.
Save hira22/bac2aa24461b71a80d76022f58fd9273 to your computer and use it in GitHub Desktop.
SwiftUIView を UITableView で使う。
import SwiftUI
import UIKit
class SwiftUIViewInUITableViewCell: UITableViewCell {
static var reuseIdentifier: String { String(describing: self) }
private var hostingController: UIViewController!
func setup<Content: View>(view: Content) {
self.hostingController = UIHostingController(rootView: view)
self.parentViewController?.addChild(self.hostingController)
self.contentView.addSubview(self.hostingController.view)
self.hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.hostingController.view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
self.hostingController.view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
self.hostingController.view.topAnchor.constraint(equalTo: self.contentView.topAnchor),
self.hostingController.view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
])
self.hostingController.didMove(toParent: self.parentViewController)
}
override func prepareForReuse() {
super.prepareForReuse()
self.hostingController.willMove(toParent: nil)
self.hostingController.view.removeFromSuperview()
self.hostingController.removeFromParent()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment