将 UIKit 集成到 SwiftUI 视图失败
这不会显示任何内容(空白屏幕):
import SwiftUI
import UIKit
struct ContentView: View {
@State var navigate = false
var body: some View {
NavigationView {
NavigationLink(destination: Text("clicked"), isActive: $navigate) {
EmptyView()
}
UIKitView {
navigate = true
}
.navigationTitle(Text("test"))
}
.navigationViewStyle(.stack)
}
}
struct UIKitView: UIViewRepresentable {
let didClick: () -> Void
func makeUIView(context _: Context) -> UIView {
MyView(didClick: didClick)
}
func updateUIView(_: UIView, context _: Context) {}
}
class MyView: UIView {
let didClick: () -> Void
init(didClick: @escaping () -> Void) {
self.didClick = didClick
super.init(frame: .zero)
backgroundColor = .red
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
addGestureRecognizer(tap)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func viewTapped(recognizer _: UIGestureRecognizer) {
didClick()
}
}
我想知道我的 UIKitView 在哪里。如果没有 NavigationLink
,它会显示,但我无法导航。
当我更改顺序(第一个 NavigationLink
而不是 UIKitView
)时,它将不再导航(并且 navigationTitle
消失了)。
如何在不使用 ZStack
的情况下使这个极其简单的示例正常工作?这是因为我在“真实”应用程序中使用了 ZStack
hack(只需将视图包装在 ZStack
内),但这会带来其他问题。
This will show nothing (blank screen):
import SwiftUI
import UIKit
struct ContentView: View {
@State var navigate = false
var body: some View {
NavigationView {
NavigationLink(destination: Text("clicked"), isActive: $navigate) {
EmptyView()
}
UIKitView {
navigate = true
}
.navigationTitle(Text("test"))
}
.navigationViewStyle(.stack)
}
}
struct UIKitView: UIViewRepresentable {
let didClick: () -> Void
func makeUIView(context _: Context) -> UIView {
MyView(didClick: didClick)
}
func updateUIView(_: UIView, context _: Context) {}
}
class MyView: UIView {
let didClick: () -> Void
init(didClick: @escaping () -> Void) {
self.didClick = didClick
super.init(frame: .zero)
backgroundColor = .red
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
addGestureRecognizer(tap)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func viewTapped(recognizer _: UIGestureRecognizer) {
didClick()
}
}
I am wondering where my UIKitView
is. Without the NavigationLink
, it is showing but than I can not navigate.
When I change the order (first NavigationLink
than UIKitView
), it won't navigate anymore (and the navigationTitle
is gone).
How can I make this extremely simple example work without using a ZStack
? This is because I use the ZStack
hack (just wrap the views inside a ZStack
) in my 'real' application, but that gives other problems down the line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论