Swift 忘记了 @State 变量

问题描述 投票:0回答:1

我在

swingPreviewLocation
中设置了一个变量
.inAppear()
但 Swift 一路上忘记了它。在
Map
视图中打印变量会返回
nil

但是:在正文中添加

Text()
,然后 Swift 会记住并打印

▿ Optional<Location>
  ▿ some : Location
    - latitude : 48.026164457627125
    - longitude : 11.958078424370319

代码:

import SwiftUI
import MapKit

struct SwingDetailView: View {
    
    var swing: Swing
    
    @State var swingPreviewLocation: Location? // Location is a struct
    
    var body: some View {
        
        VStack {
            // This helps keep the variable. If I remove it, swift forgets the variable later.
            if let latitude = swingPreviewLocation?.latitude,
               let longitude = swingPreviewLocation?.longitude {
                Text("Latitude: \(Int(latitude)), Longitude: \(Int(longitude))")
            }
            MapReader { reader in
                Map () {
                    let _ = print(self.swingPreviewLocation)
                    if let location = self.swingPreviewLocation {
                        Annotation("Club", coordinate: CLLocation(latitude: location.latitude, longitude: location.longitude).coordinate) {
                            Text("C")
                        }
                    }
                }
            }
            .onAppear() {
                self.swingPreviewLocation = swing.location
            }
        }
    }
}

class Swing {
    let location: Location?
    init(location: Location?) {
        self.location = location
    }
}


struct Location {
    var latitude: Double
    var longitude: Double
}
ios swift swiftui
1个回答
0
投票

问题出在

MapReader()

不知何故,Swift 丢失了 MapReader 闭包内 @State 变量的值。

简单的解决方法:

if let location = swingPreviewLocation { 
    MapReader { reader in
        Map (interactionModes: [.pan, .zoom]) {
...
© www.soinside.com 2019 - 2024. All rights reserved.