如何在 SwiftUI 视图中调用方法

2024-04-15

刚刚开始使用 SwiftUI。

我有一个谷歌地图视图 https://gist.github.com/kwmt/1df17577c59e33da1c4c2eb982f21bbf in a ContentView使用CLLocationManager我捕捉事件AppDelegate or SceneDelegate通过扩展它们来类CLLocationManagerDelegate.

我怎样才能调用一个方法GoogleMapsView来自AppDelegate or SceneDelegate?

在这种情况下我想调用.animate方法,当位置更改事件发送到AppDelegate实例通过CLLocationManagerDelegate,但这个问题确实更通用。


我制作并实现了 CLLocationManager 和 MKMapView,它与地图几乎相同,希望对您有所帮助:

简短回答: 声明一个@Binding var foo: Any每次 foo 更改时,您都可以在 GoogleMapView 内进行更改,在本例中 foo 是您的位置,因此您可以在每次更新 foo 时调用 animate。

长答案:

首先,我创建了一个符合 UIViewRepresentable 协议的 Mapview,就像您所做的那样,但添加了 @Binding 变量,这是我的“trigger".

MapView:

struct MapView: UIViewRepresentable {
    @Binding var location: CLLocation // Create a @Binding variable that keeps the location where I want to place the view, every time it changes updateUIView will be called
    private let zoomMeters = 400

    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        let mapView = MKMapView(frame: UIScreen.main.bounds)
        return mapView
    }

    func updateUIView(_ mapView: MKMapView, context: Context) {
        //When location changes, updateUIView is called, so here I move the map:
        let region = MKCoordinateRegion(center: location.coordinate,
                                        latitudinalMeters: CLLocationDistance(exactly: zoomMeters)!,
                                        longitudinalMeters: CLLocationDistance(exactly: zoomMeters)!)
        mapView.setRegion(mapView.regionThatFits(region), animated: true)
    }
}

然后我将 MapView 放置在 ContentView 中,并传递一个位置参数,接下来我将对此进行解释:

内容视图:

struct ContentView: View {

    @ObservedObject var viewModel: ContentViewModel

    var body: some View {
        VStack {
            MapView(location: self.$viewModel.location)
        }
    }
}

在我的 ViewModel 中,我使用委托处理位置更改,以下是注释中包含更多详细信息的代码:

class ContentViewModel: ObservableObject {
    //location is a Published value, so the view is updated every time location changes
    @Published var location: CLLocation = CLLocation.init()

    //LocationWorker will take care of CLLocationManager...
    let locationWorker: LocationWorker = LocationWorker()

    init() {
        locationWorker.delegate = self
    }

}

extension ContentViewModel: LocationWorkerDelegate {
    func locationChanged(lastLocation: CLLocation?) {
        //Location changed, I change the value of self.location, it is a @Published value so it will refresh the @Binding variable inside MapView and call MapView.updateUIView
        self.location = CLLocation.init(latitude: lastLocation!.coordinate.latitude, longitude: lastLocation!.coordinate.latitude)
    }
}

最后是 LocationWorker,它负责 CLLocationManager():

class LocationWorker: NSObject, ObservableObject  {

    private let locationManager = CLLocationManager()
    var delegate: LocationWorkerDelegate?

    let objectWillChange = PassthroughSubject<Void, Never>()

    @Published var locationStatus: CLAuthorizationStatus? {
        willSet {
            objectWillChange.send()
        }
    }

    @Published var lastLocation: CLLocation? {
        willSet {
            objectWillChange.send()
        }
    }

    override init() {
        super.init()
        self.locationManager.delegate = self
        //...
    }
}

protocol LocationWorkerDelegate {
    func locationChanged(lastLocation: CLLocation?)
}

extension LocationWorker: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.lastLocation = location
        //When location changes: I use my delegate ->
        if delegate != nil {
            delegate!.locationChanged(lastLocation: lastLocation)
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 SwiftUI 视图中调用方法 的相关文章

随机推荐

  • Java 中保存最后 N 个元素的大小受限队列

    关于 Java 库的一个非常简单快速的问题 是否有一个现成的类可以实现Queue具有固定的最大大小 即它始终允许添加元素 但它会默默地删除头元素以为新添加的元素提供空间 当然 手动实现它很简单 import java util Linked
  • 如何检测 highcharts 中的缩放事件?

    是否可以检测 Highcharts 中的缩放事件 我的用例是 我有一些图表外部的状态 当用户放大其中的一部分时 我想检测 x 轴上的新时间范围并更新相应的外部状态 你有没有尝试过高图表API http api highcharts com
  • 需要帮助解决 sorl-thumbnail 错误:“‘thumbnail’不是有效的标签库:”

    我一直在绞尽脑汁试图解决这个问题 我已经尝试了一切 但我没有任何想法 我不断看到这个错误 异常值 thumbnail 不是有效的标签库 无法从 django templatetags thumbnail 加载模板库 没有名为 sorl th
  • std::initializer_list 和引用类型

    Can a std initializer list包含引用类型 右值和左值 或者是否必须使用指针或引用包装器 例如std ref EDIT 也许需要更多澄清 我有一个成员变量 std vector
  • R 中的 Unicode 下标

    我想写 sigma 2 i使用 unicode 我可以得到三分之二的方法 u03C3 U00B2 我一生都无法弄清楚如何添加下标 根据在这个网站上我得到了上标 2 的 unicode http www fileformat info inf
  • Silex - app->json() 以字符串形式返回整数数据

    我刚刚开始使用 Silex 来帮助我构建一个从 MySQL 数据库返回数据的 Restful API 以前在使用 php 和 mysql 时 我注意到 MySQL 会在我的文件中将整数作为字符串返回json encode 功能 它会在我的所
  • iTunes Connect 上的销售统计数据多久更新一次? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我的应用程序今天被 Apple 接受 我正在尝试计算它已被下载了多少次 有谁知道 iTunes Con
  • npm install git+ssh 在 docker (node16) 中失败

    谁能解释一下为什么要从node 14 alpine to node 16 alpine会导致npm安装失败吗 gt 8 10 RUN mount type ssh npm i 14 14 27 npm ERR code 128 14 14
  • InProc 会话数据消失

    我大约一周前才注意到这一点 我正在存储有关用户正在玩的当前谜题的数据 www wikipediamaze com 如下所示 HttpContext Current Session Add puzzleInfo currentPuzzleIn
  • 使用 jQuery 将宽度设置为百分比

    如何使用 jQuery 将 div 的宽度设置为百分比 使用width http api jquery com width 功能 div somediv width 70 将转向 div div into div style width 7
  • 如何将CUDA时钟周期转换为毫秒?

    我想用一些代码来测量时间within我的内核需要 我已经关注了这个问题 https stackoverflow com questions 11209228 timing different sections in cuda kernel连
  • 如何将图像从黑色转换为白色,反之亦然

    我有一张黑白的 jpg 图片 我想将黑色部分转换为白色 将白色部分转换为黑色 黑色像素转换为白色 反之亦然 MATLAB并再次另存为jpg文件 我已经尝试过这段代码 但它只是在白页上给了我一条黑线 im imread Export00000
  • JPA/Hibernate + HQL/JPQL:选择带有 BigDecimal 参数的 DTO

    我们使用 JPA 和 hibernate 作为实现 假设我有以下 DTO public class SupplierInfoDto private String supplierName private BigDecimal remaini
  • iOS 11 SceneKit hitTest:选项:失败

    我在 iOS 11 上的 SceneKit 中使用 hitTest options 时遇到了困难 在地图应用程序中 我有一个地形节点 使用 hitTest options 我能够长时间通过触摸屏幕来发现地形上的一个点 它仍然可以在 iOS
  • 反应路由器和 Express 冲突

    我有我想要 React Router 处理的路径 而且我还有一个 Express API 后端 我从 React 应用程序调用它来执行一些安全的 API 调用 希望在这里提供应用程序 id 应用程序的唯一 URL 我使用 ID 从 Reac
  • 如何将 com.android.internal.telephony.ITelephony 导入到 Android 应用程序

    我想挂断来电 我检测到它然后我想挂断它 问题是这样的 com android internal telephony ITelephony没有解决 我尝试添加包com android internal telephony到我的应用程序并创建界
  • 在 Puppeteer 中获取 elementHandle 的同级元素

    我正在做 const last await page item last child 现在我很想根据最后一个元素获取前面的元素 IE const prev last prev 关于如何做到这一点有什么想法吗 Thanks 你应该使用prev
  • 异常传播指南(Java 中)

    Java 中有关于异常传播的指南吗 什么时候向方法签名添加异常 例如 如果仅在缺少必要的程序资源时抛出异常 并且只能在顶层处理 那么我是否可以通过使用错误方法的所有方法将其传播到使用此异常的所有方法 有什么好的做法吗 有什么不好的做法吗 如
  • 使用javascript更改html标签内的文本

    我正在尝试使用纯 JavaScript 更改 li 标记内的文本 html 内容始终是这样的 section class sidebar menu sidebar right sidebar open div class cart side
  • 如何在 SwiftUI 视图中调用方法

    刚刚开始使用 SwiftUI 我有一个谷歌地图视图 https gist github com kwmt 1df17577c59e33da1c4c2eb982f21bbf in a ContentView使用CLLocationManage