【问题标题】:Simple assignment operation in init method does not work swiftuiinit 方法中的简单赋值操作不起作用 swiftui
【发布时间】:2020-04-11 03:16:26
【问题描述】:

我是 iOS 新手,现在正尝试在 swiftui 视图中实现我自己的 init 方法。 Init 有一个参数,必须为两个 State 赋值。但是,无论我做什么,它都不能正确填充它们。我使用 MapKit 和 CLLocationCoordinate2D 进行地理定位。 只是补充一下,坐标: init 中的 CLLocationCoordinate2D 具有正确的值,但状态没有。 我在这里实现的视图是 ModalView 知道该怎么做吗?这是我的代码。


    @State var coordinate = CLLocationCoordinate2D()
    @State private var name: String = ""
    @State private var price: Decimal = 0
    @State private var priceStr: String = ""
    @State private var showAlert = false
    @State private var location = ParkPlaceRespons(id: -1, name: "", price: -0, longitude: 18.42645, latitude: 43.85623)
    @State private var mapArray = [ParkPlaceRespons]()

    var alert: Alert{
        Alert(title: Text("Error"), message: Text("Your price input is not in right format"), dismissButton: .default(Text("Ok")))}

    init(coordinates: CLLocationCoordinate2D){
        print(coordinates)    // CLLocationCoordinate2D(latitude: 43.85613, longitude: 18.42745)
        self.coordinate = coordinates
        print(self.coordinate)   // CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
        self.coordinate.latitude = coordinates.latitude
        self.coordinate.longitude = coordinates.longitude
        self.location.longitude = coordinates.longitude
        self.location.latitude = coordinates.latitude
        print(location)  // Does not work as well
        self.mapArray.append(location)
        print(mapArray)   // Empty array
    }

【问题讨论】:

    标签: mapkit swiftui init swift5 modal-view


    【解决方案1】:

    当您查看有关 @State 的文档时,您会发现以下片段:

    只能从视图主体内部(或从 它调用的函数)。因此,您应该声明您的 将属性声明为私有,以防止您视图的客户 访问它。

    因此,您不应在初始化程序中设置坐标、位置或 mapArray,如果您发现有必要在初始化程序中设置变量,您应该将它们声明为 @Binding@ObservedObject

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 2020-09-18
      • 2014-06-20
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2018-12-16
      • 2012-10-04
      相关资源
      最近更新 更多