Created
July 29, 2021 05:55
-
-
Save hira22/bac2aa24461b71a80d76022f58fd9273 to your computer and use it in GitHub Desktop.
SwiftUIView を UITableView で使う。
This file contains 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
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