swift - UIViewRepresentable updateUIView() 使用 .sheet() 时的奇怪行为
问题描述
我刚刚发现 SwiftUI 的 UIViewRepresentable 有一些奇怪的行为。我不确定这是一个错误,还是我理解 SwiftUI 的错误。我做了小复制来显示问题。
我为 MKMapView 创建了 UIViewRepresentable:
import SwiftUI
import MapKit
struct UIMap: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView(frame: .zero)
map.delegate = context.coordinator
return map
}
func updateUIView(_ map: MKMapView, context: Context) {
print("Change!")
}
func makeCoordinator() -> UIMapCoordinator {
return UIMapCoordinator(self)
}
class UIMapCoordinator: NSObject, MKMapViewDelegate {
var parent: UIMap
init(_ parent: UIMap) {
self.parent = parent
}
}
}
然后我为这个可表示的创建非常小的包装器:
import SwiftUI
struct MapWrapper: View {
var body: some View {
UIMap()
}
}
最后我在 ContentView 中使用它:
import SwiftUI
struct ContentView: View {
@State private var showSheet = false
@State private var showButton = true
var body: some View {
ZStack(alignment: .bottom){
MapWrapper()
HStack{
if showButton {
Button(action: { showSheet = true }){
Text("Show Sheet")
}
.foregroundColor(.yellow)
}
Spacer()
Button(action: { showButton = !showButton }){
Text("Toggle Button")
}
.foregroundColor(.yellow)
}
}
.sheet(isPresented: $showSheet) {
Text("Sheet content")
}
}
}
我在 ContentView 中有两个可点击元素 - 一个用于打开工作表,另一个用于隐藏按钮(只是为了查看状态更改)。打开工作表(更改showSheet
为true
)会导致updateUIView
被调用(“更改!”在调试控制台中打印),而更改showButton
不会这样做。看起来打开表改变了MapWrapper
(?)的状态。这种行为正确吗?
解决方案
推荐阅读
- javascript - 尽管使用了语言环境文件,但在 moment.js 中设置语言环境仍不起作用
- asp.net - 似乎无法使启用迁移工作成功安装但未添加
- python - 在烧瓶中从python导入html
- javascript - 单页应用中的多个地址参数
- reactjs - 在 React 中路由后如何调用函数?
- kotlin - Intellij 在 Kotlin 的注释字段之前禁用新行
- html - 在 CSS 中响应式缩放 SVG
- excel - 通过引用其他单元格中包含的工作表的名称来获取不同工作表中单元格的值
- python - 如何在 django 中使用 get_absolute_url 将字符串添加到我的博客文章路径而不是整数?
- flask - 从 Angular 向烧瓶应用程序提交表单时收到 CORS 策略错误