有没有办法动态加载UserAnnotation()或者自定义闭包版本UserAnnotation(){}?

问题描述 投票:0回答:1

使用标准

Map()
初始化程序,我想显示 UserAnnotation() 视图或使用
UserAnnotation(){}
闭包创建我自己的视图。

我需要由布尔值触发它。

我创建了一个示例视图,如果我将其设置为声明的值,则

if/else
语句可以正常工作,但是当我在运行时/预览中切换它时,它仍然使用声明的值。

我在

if/else
之前有一个 print 语句,它似乎忽略了这一点?

我已经尝试过使用本地声明的

var Bool
$State
@AppStorage
以及本例中的
@Published
,但我仍然无法让它使用按钮中的切换值进行测试。它始终使用声明的初始值。

感谢任何见解或解决方法来实现这一目标..谢谢

import SwiftUI
import MapKit

final class TestingViewModel: ObservableObject {
    @Published var showArrowToTarget = false  // changing here is the only place that works
}
struct TestingView: View {
    @StateObject private var viewModel = TestingViewModel()
    var body: some View {
        Map(initialPosition: .userLocation(fallback: .automatic)){
            let _ = print("isShowingCustom = \( viewModel.showArrowToTarget)")
            if viewModel.showArrowToTarget {
                UserAnnotation(){
                    Text("showArrowToTarget").font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
                    let _ = print("..CustomUserAnnotation isShowingCustom = \( viewModel.showArrowToTarget)")
                }
            } else {
                UserAnnotation()
                let _ = print("..UserAnnotation isShowingCustom =  \( viewModel.showArrowToTarget)")
            }
        }
        .safeAreaInset(edge: .top){
            // Press this to toggle true/false works but refers to initialised value in the if/else ???
            Button("Toggle showArrowToTarget showArrowToTarget= \(viewModel.showArrowToTarget)"){
                viewModel.showArrowToTarget.toggle()
                let _ = print("..toggle to  \( viewModel.showArrowToTarget)")
            }
        }
    }
}

#Preview {
    TabView{
        TestingView()
    }
}
swiftui mapkit mkuserlocation
1个回答
0
投票

我尝试了很多方法,但没有成功。恕我直言,也许

UserAnnotation
从第一次初始化时就附加在
Map
内。它与
Marker
不同,后者可以在 Map 的生命周期内替换。因此,有一种解决方法可以在
Map
发生变化时强制重绘整个
viewModel.showArrowToTarget

注意:这是一种完全浪费且无效的方式,所以这将是最后的选择。


@State private var mapID = UUID()

...
Map {
    if viewModel.showArrowToTarget {
        UserAnnotation() {
            Text("showArrowToTarget")
                .font(.title)
        }
    } else {
        UserAnnotation()
    }
}
.id(mapID) //<- force here
© www.soinside.com 2019 - 2024. All rights reserved.