SwiftUI-将数据从数组传递到结构

时间:2020-07-08 13:25:58

标签: swiftui

我很难将数据从数组传递到WeatherWidget,后者通过WidgetView传递每个项目。 我相信这与我声明@State的方式有关。

// ContentView

struct WeatherWidget: View {

    @State var weather = weatherData
    @State var index = 0
    
    var body: some View {
        ScrollView (.vertical, showsIndicators: false){
            TabView(selection: self.$index) {
                ForEach(weatherData) { weather in
                    WidgetView(data: weather)
                        // Identifies current index
                        .tag(self.index)
                }
            }
            .animation(.easeOut)
        }
        .animation(.easeOut)
    }
}

//小部件

struct WidgetView: View {

    @State var data: Weather
    
    var body: some View {
        HStack(alignment: .top) {
            VStack(alignment: .leading) {
                Text(data.temp)
                    .foregroundColor(.white)
                    .font(.system(size: 24))
                    .fontWeight(.semibold)
                    .padding(.bottom, 16)
                Text(data.city)
                    .foregroundColor(.white)
                    .padding(.bottom, 4)
                Text(data.range)
                    .foregroundColor(.gray)
            }
            Image(systemName: data.icon)
                .font(.system(size: 32, weight: .medium))
                .foregroundColor(.yellow)
        }
        .padding()
        .frame(width: 185, height: 169)
        .background(RoundedRectangle(cornerRadius: 24, style: .continuous).fill(Color.black.opacity(0.8)))
    }
}

//天气结构

struct Weather : Hashable, Identifiable {

    var id = UUID()
    var temp : String
    var city : String
    var range : String
    var icon : String
}

//数据数组


var weatherData = [

    Weather(temp: "26°C", city: "Toronto, ON", range: "17°C / 28°C", icon: "sun.max"),
    Weather(temp: "17°C", city: "Waterloo, ON", range: "14°C / 24°C", icon: "cloud.rain"),
    Weather(temp: "31°C", city: "Whitby, ON", range: "24°C / 32°C", icon: "cloud.bolt.rain")
]

0 个答案:

没有答案