【问题标题】:Can't Connect and Input field to the to the Function/Class无法连接和输入字段到函数/类
【发布时间】:2020-12-08 09:46:19
【问题描述】:

我们有一个大型函数/类,它位于我们的输入字段(TextField 值)所在的结构之外。由于某种原因,我们无法将字段连接到函数。

我们要完成的工作:拥有我们创建的算法/函数,在单击按钮时使用,然后与 MapView 一起使用。使变量全局可访问

到目前为止我们所做的尝试:将整个类粘贴到 MenuTabView 结构中,@EnviromentalObject,在代码的第一个 sn-p 中简单调用函数。

这是我们当前的 HStack 视图

  HStack {​
            Button(action: {​
                // FIXME: Here should be some action for calculating the route -> hopefully with light data
                MapView.plotRoute(sourceLat: 52.38916893852631, sourceLon: 13.119924894109332, destinationLat: 52.395251383040865, destinationLon: 13.128239742045292)
            }​) {​
                Text("Find Route")
                    .foregroundColor(.white)
                    .bold()
            }​.padding()
        }​

这是我们的 MapView:UIViewRepresentable variables {

import SwiftUI
import MapKit
import CoreLocation

struct MapView: UIViewRepresentable {
    @Binding var directions: [String]
    @Binding var checkpoints: [Checkpoint]
    var mapView = MKMapView(frame: UIScreen.main.bounds)
    var locationManager = CLLocationManager()

以下是我们希望“随处”可访问的变量

// The State for the directions display
@State private var showDirections = false
// Set the coordinates for the test checkpoints
@State var checkpoints: [Checkpoint] = [
  Checkpoint(title: "Test Lamp", coordinate: .init(latitude: 52.387797, longitude: 13.119534))
]

我知道代码没有多大帮助,但不幸的是,我无法在此处发布所有 HStack 和类/函数。

这是错误:

实例成员 'plotRoute' 不能用于类型 'MapView';你是否 意思是改用这种类型的值? MapTabView.swift

当我们试图调用函数的一部分时,Swift 会显示错误

谢谢!

【问题讨论】:

  • 您是否尝试过将变量声明为静态变量,或者如果它们真的给您带来麻烦,甚至可以将它们保存到 UserDefaults。

标签: swift function struct swiftui textfield


【解决方案1】:

问题在于plotRoute 是MapView 的实例方法,但您试图在类型而不是实例上调用它。

如果该方法确实是类型方法,则应将其声明更改为static func plotRoute(...,然后您就可以将其称为MapView.plotRoute...。

如果该方法使用MapView 的实例属性,那么您需要在您的View 中创建一个MapView 实例并在其上调用该方法。

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多