【问题标题】:@State private variable is immutable@State 私有变量是不可变的
【发布时间】:2021-02-01 13:06:14
【问题描述】:

我对 Swift 比较陌生,我正在尝试使用 MapKit 创建一个视图。

我必须将绑定坐标区域传递给Map(),该区域存储在@State 变量中。但是,当我尝试初始化此变量时,错误是 Cannot assign to property: '$region' is immutable

这是代码:

struct MapView: View {
  @State private var region: MKCoordinateRegion
  var body: some View {
    Map(coordinateRegion: $region)
  }
  init(_ location: CLLocationCoordinate2D) {
    $region = MKCoordinateRegion( // Cannot assign to property: '$region' is immutable
        center: location,
        span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
      )
  }
}

这可能是一个简单的解决方法,但我在互联网上找不到任何东西。

谢谢

【问题讨论】:

    标签: swift struct swiftui state


    【解决方案1】:

    你可以像这样使用State(initialValue:)

    struct MapView: View {
      @State private var region: MKCoordinateRegion
      var body: some View {
        Map(coordinateRegion: $region)
      }
      init(_ location: CLLocationCoordinate2D) {
        self._region = State(initialValue: MKCoordinateRegion(
            center: location,
            span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
          ))
      }
    }
    

    【讨论】:

    • 这成功了!谢谢你。为什么我不能用 $region 引用 region,而必须使用 self?
    • @NilsSchwebel 这不是关于self,而是关于添加下划线(_region)。 This 可能会对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多