草庐IT

关于ios:SwiftUI MapKit UIViewRepresentable Can’t present Alert

codeneng 2023-03-28 原文

SwiftUI MapKit UIViewRepresentable Can't present Alert

我有一个 SwiftUI 应用程序,其中有几个视图是使用 MapKit 制作的地图
UIView 可表示的。我有兴趣点和使用的自定义注释
右侧和左侧的标注按钮,用于进一步操作。在右边我只是想要
显示有关航点的信息。在左边我想发出警报
进一步操作的选择 - 例如,插入一个新的注释点。前
SwiftUI 我刚刚提出了一个警报,并做了上述两个。但据我所知,
UIViewRepresentable 版本上没有 self.present。因此我没有
能够显示警报。

只是为了一个实验 - 我将 SwiftUI 警报代码附加到 SwiftUI 视图中
调用 MapView。使用 Observable 布尔值,我确实可以同时发出这两个警报。
这对我来说似乎很奇怪,但也许是绑定到全局属性的警报代码
可以在任何地方。

我的第一次尝试:(结构是 DetailMapView)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    if control == view.leftCalloutAccessoryView {
        guard let tappedLocationCoord = view.annotation?.coordinate else {return}
        let tappedLocation = CLLocation(latitude: tappedLocationCoord.latitude, longitude: tappedLocationCoord.longitude)

        let ac = UIAlertController(title: nil, message: nil, preferredStyle: .alert)

        let deleteAction = UIAlertAction(title:"Delete Waypoint", style: .destructive) { (action) in
            //some stuff
        }

        let insertAction = UIAlertAction(title:"Insert Waypoint After This", style: .default) { (action) in
            //some stuff
        }

        let cancelAction = UIAlertAction(title:"Cancel", style: .default) { (action) in
            //some stuff
        }//cancelAction

        ac.addAction(deleteAction)
        ac.addAction(insertAction)
        ac.addAction(cancelAction)

        //tried adding self, referencing parent - always error saying
        //the object does not have a .present
        mapView.present(ac, animated: true)

    } else if control == view.rightCalloutAccessoryView {
        //more of the same
    }
}//annotationView

然后我删除了警报代码并添加了:

1
parent.userDefaultsManager.shouldShowAnnotationEditMenu.toggle()

然后我将呼叫屏幕更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@ObservedObject var userDefaultsManager: UserDefaultsManager
var aTrip: Trip?

var body: some View {

    VStack {
        Text(aTrip?.name ??"Unknown Map Name")
            .padding(.top, -50)
            .padding(.bottom, -20)

        DetailMapView(aTrip: aTrip, userDefaultsManager: userDefaultsManager)
            .padding(.top, -20)
            .alert(isPresented: $userDefaultsManager.shouldShowAddress) {
                //Alert(title: Text("\\(aTrip?.name ??"No") Address"),
                Alert(title: Text(self.userDefaultsManager.approximateAddress),
                      message: Text("This is the approximate street address."),
                      dismissButton: .default(Text("Got it!")))
            }//.alert shouldShowAddress

        Text("This is the view where the trip information will be displayed.")
            .multilineTextAlignment(.center)
        .alert(isPresented: $userDefaultsManager.shouldShowAnnotationEditMenu) {
            Alert(title: Text("Edit Annotations"),
                  message: Text("Choose this to insert an Annotation."),
                  dismissButton: .default(Text("Got it!")))
        }//.alert shouldShowAddress
    }
}

我想如果这是安全的,我可以让它工作 - 但它似乎更复杂
应该是。

这就是想法:

任何指导将不胜感激:Xcode 版本 11.3.1 (11C504)


我为此花了一个小时,我是 SwiftUI 的新手,我跳进去只是为了回答一些简单的问题。

一种方法是使用 Bool(@State@Binding)。

你还需要有一个View而不是直接在你的SceneDelegate中使用你的UIViewRepresentable。因为那是你将链接 alert.

的地方

像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct MainView: View {
    @State var text =""
    @State var showingAlert: Bool

    var body: some View {
        VStack {
            MapView(showingAlert: self.$showingAlert)
                .alert(isPresented: $showingAlert) { () -> Alert in
                    print("SHOWING ALERT BODY: --> \\($showingAlert.wrappedValue)")
                    return Alert(title: Text("Important message"), message: Text("Go out and have a girlfriend!"), dismissButton: .default(Text("Got it!")))
            }
        }
    }
}

然后你的 MapView 应该是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct MapView: UIViewRepresentable {

    let landmarks = LandmarkAnnotation.requestMockData()

    @Binding var showingAlert: Bool

    func makeCoordinator() -> MapViewCoordinator {
        MapViewCoordinator(mapView: self, showingAlert: self.$showingAlert)
    }

    /**
     - Description - Replace the body with a make UIView(context:) method that creates and return an empty MKMapView
     */
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context){
        //If you changing the Map Annotation then you have to remove old Annotations
        //mapView.removeAnnotations(mapView.annotations)
        view.delegate = context.coordinator
        view.addAnnotations(landmarks)
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(showingAlert: Binding<Bool>.constant(true))
    }
}

最后,在你的 MapViewCoordinator 中(我想你有这个类,这是实现 MKMapViewDelegate 的委托方法的类。)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
 Coordinator for using UIKit inside SwiftUI.
 */
class MapViewCoordinator: NSObject, MKMapViewDelegate {

    var mapViewController: MapView!
    @Binding var showAlert: Bool

    init(mapView: MapView, showingAlert: Binding<Bool>) {

        self.mapViewController = mapView
        self._showAlert = showingAlert
        super.init()
    }

    func mapView(_ mapView: MKMapView, viewFor
        annotation: MKAnnotation) -> MKAnnotationView?{
        //Custom View for Annotation
        let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier:"customView")
        annotationView.canShowCallout = true
        //Your custom image icon
        annotationView.image = UIImage(named:"locationPin")
        return annotationView
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        print("calloutAccessoryControlTapped")
    }

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        print("didSelect")

        self.showAlert = true
    }
}

如您所见,我只是使用了 Bool 标志。尤其是 @Binding 那个。


是的,格伦。

这实际上是我的做法。我用过ObservedObjects。但是我认为您使用 @State@Binding 的方法更好。
另外,我不想有条件地显示地图 - 只想显示注释连接。
由于某种原因,我无法对您的答案添加评论,所以在这里回复。

  • 请使用您问题上的编辑链接添加其他信息。 Post Answer 按钮应仅用于问题的完整答案。 - 来自评论

有关关于ios:SwiftUI MapKit UIViewRepresentable Can’t present Alert的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  5. ruby-on-rails - Ruby 流量控制 : throw an exception, 返回 nil 还是让它失败? - 2

    我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id

  6. ruby-on-rails - 关于 Ruby 的一般问题 - 2

    我在我的rails应用程序中安装了来自github.com的acts_as_versioned插件,但有一段代码我不完全理解,我希望有人能帮我解决这个问题class_eval我知道block内的方法(或任何它是什么)被定义为类内的实例方法,但我在插件的任何地方都找不到定义为常量的CLASS_METHODS,而且我也不确定是什么here,并且有问题的代码从lib/acts_as_versioned.rb的第199行开始。如果有人愿意告诉我这里的内幕,我将不胜感激。谢谢-C 最佳答案 这是一个异端。http://en.wikipedia

  7. ruby - 我怎样才能更好地了解/了解更多关于 Ruby 的知识? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我最近开始学习Ruby,这是我的第一门编程语言。我对语法感到满意,并且我已经完成了许多只教授相同基础知识的教程。我已经写了一些小程序(包括我自己的数组排序方法,在有人告诉我谷歌“冒泡排序”之前我认为它非常聪明),但我觉得我需要尝试更大更难的东西来理解更多关于Ruby.关于如何执行此操作的任何想法?

  8. ruby - 关于 Ruby 中 Dir[] 和 File.join() 的混淆 - 2

    我在Ruby中遇到了一个关于Dir[]和File.join()的简单程序,blobs_dir='/path/to/dir'Dir[File.join(blobs_dir,"**","*")].eachdo|file|FileUtils.rm_rf(file)ifFile.symlink?(file)我有两个困惑:首先,File.join(@blobs_dir,"**","*")中的第二个和第三个参数是什么意思?其次,Dir[]在Ruby中有什么用?我只知道它等价于Dir.glob(),但是,我对Dir.glob()确实不是很清楚。 最佳答案

  9. elasticsearch源码关于TransportSearchAction【阶段三】 - 2

    1.回顾.TransportServicepublicclassTransportServiceextendsAbstractLifecycleComponentTransportService:方法:1publicfinalTextendsTransportResponse>voidsendRequest(finalTransport.Connectionconnection,finalStringaction,finalTransportRequestrequest,finalTransportRequestOptionsoptions,TransportResponseHandlerT>

  10. 关于Qt程序打包后运行库依赖的常见问题分析及解决方法 - 2

    目录一.大致如下常见问题:(1)找不到程序所依赖的Qt库version`Qt_5'notfound(requiredby(2)CouldnotLoadtheQtplatformplugin"xcb"in""eventhoughitwasfound(3)打包到在不同的linux系统下,或者打包到高版本的相同系统下,运行程序时,直接提示段错误即segmentationfault,或者Illegalinstruction(coredumped)非法指令(4)ldd应用程序或者库,查看运行所依赖的库时,直接报段错误二.问题逐个分析,得出解决方法:(1)找不到程序所依赖的Qt库version`Qt_5'

随机推荐