Skip to content

Instantly share code, notes, and snippets.

@yimajo
Created June 17, 2021 10:22
Show Gist options
  • Save yimajo/1e0898d8a937891c4f5360e443f0e724 to your computer and use it in GitHub Desktop.
Save yimajo/1e0898d8a937891c4f5360e443f0e724 to your computer and use it in GitHub Desktop.
SwiftUIのNavigationView下にある階層にUIKitが挟まるとNavigationLinkが動作しないんじゃが?
import UIKit
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
// UIKitのViewを使う。こいつの階層内でNavigationLinkしてみる
MyUIKitContentsView()
}
.navigationTitle("Title")
}
}
}
struct MyUIKitContentsView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: Context) {}
func makeUIView(context: Context) -> UIView {
let myView = MyUIKitView<MyNavigationView>()
myView.setView(MyNavigationView())
return myView
}
}
class MyUIKitView<T: View>: UIView {
private let hostingController = UIHostingController<T?>(rootView: nil)
override init(frame: CGRect) {
hostingController.view.backgroundColor = .clear
hostingController.view.clipsToBounds = true
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setView(_ view: T) {
hostingController.rootView = view
addSubview(hostingController.view)
let constraints = [
hostingController.view.topAnchor.constraint(
equalTo: self.topAnchor,
constant: 0
),
hostingController.view.leftAnchor.constraint(
equalTo: self.leftAnchor,
constant: 0
),
hostingController.view.bottomAnchor.constraint(
equalTo: self.bottomAnchor,
constant: 0
),
hostingController.view.rightAnchor.constraint(
equalTo: self.rightAnchor,
constant: 0
),
]
NSLayoutConstraint.activate(constraints)
}
}
struct MyNavigationView: View {
var body: some View {
NavigationLink(
destination: Text("destination"),
label: { Text("myNavigation") }
)
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment