【发布时间】:2021-12-26 07:33:58
【问题描述】:
我正在尝试将 .refreshable 添加到我的 SwiftUI openweathermap 应用程序中,以便下拉和刷新从 API 返回到应用程序的值。我将我的应用程序设置为允许用户在文本字段中输入城市名称,点击搜索按钮,然后在工作表中查看该城市的天气详细信息。关闭表格后,用户可以在列表中以导航链接的形式查看他/她之前搜索过的所有城市,每个列表链接中都可以看到城市名称和温度。我试图将.refreshable {} 添加到我的 ContentView 的列表中。我尝试在我的 ViewModel 中设置 .refreshable 以调用 fetchWeather(),而后者又设置为将用户输入的 cityName 作为参数传递到 API URL(也在 ViewModel 中)。但是,我现在认为这不会刷新天气数据,因为调用fetchWeather() 的操作是在工具栏按钮中定义的,而不是在列表中。知道如何设置 .refreshable 来刷新列表中每个搜索城市的天气数据吗?请参阅下面的代码。谢谢!
内容视图
struct ContentView: View {
// Whenever something in the viewmodel changes, the content view will know to update the UI related elements
@StateObject var viewModel = WeatherViewModel()
@State private var cityName = ""
@State private var showingDetail = false
var body: some View {
NavigationView {
VStack {
List {
ForEach(viewModel.cityNameList) { city in
NavigationLink(destination: DetailView(detail: city), label: {
Text(city.name).font(.system(size: 32))
Spacer()
Text("\(city.main.temp, specifier: "%.0f")°").font(.system(size: 32))
})
}.onDelete { index in
self.viewModel.cityNameList.remove(atOffsets: index)
}
}.refreshable {
viewModel.fetchWeather(for: cityName)
}
}.navigationTitle("Weather")
.toolbar {
ToolbarItem(placement: (.bottomBar)) {
HStack {
TextField("Enter City Name", text: $cityName)
.frame(minWidth: 100, idealWidth: 150, maxWidth: 240, minHeight: 30, idealHeight: 40, maxHeight: 50, alignment: .leading)
Spacer()
Button(action: {
viewModel.fetchWeather(for: cityName)
cityName = ""
self.showingDetail.toggle()
}) {
HStack {
Image(systemName: "plus")
.font(.title)
}
.padding(15)
.foregroundColor(.white)
.background(Color.green)
.cornerRadius(40)
}.sheet(isPresented: $showingDetail) {
ForEach(0..<viewModel.cityNameList.count, id: \.self) { city in
if (city == viewModel.cityNameList.count-1) {
DetailView(detail: viewModel.cityNameList[city])
}
}
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
详细视图
struct DetailView: View {
@StateObject var viewModel = WeatherViewModel()
@State private var cityName = ""
@State var selection: Int? = nil
var detail: WeatherModel
var body: some View {
VStack(spacing: 20) {
Text(detail.name)
.font(.system(size: 32))
Text("\(detail.main.temp, specifier: "%.0f")°")
.font(.system(size: 44))
Text(detail.firstWeatherInfo())
.font(.system(size: 24))
}
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView(detail: WeatherModel.init())
}
}
视图模型
class WeatherViewModel: ObservableObject {
@Published var cityNameList = [WeatherModel]()
func fetchWeather(for cityName: String) {
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(cityName)&units=imperial&appid=<MyAPIKey>") else { return }
let task = URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else { return }
do {
let model = try JSONDecoder().decode(WeatherModel.self, from: data)
DispatchQueue.main.async {
self.cityNameList.append(model)
}
}
catch {
print(error) // <-- you HAVE TO deal with errors here
}
}
task.resume()
}
}
型号
struct WeatherModel: Identifiable, Codable {
let id = UUID()
var name: String = ""
var main: CurrentWeather = CurrentWeather()
var weather: [WeatherInfo] = []
func firstWeatherInfo() -> String {
return weather.count > 0 ? weather[0].description : ""
}
}
struct CurrentWeather: Codable {
var temp: Double = 0.0
}
struct WeatherInfo: Codable {
var description: String = ""
}
【问题讨论】:
标签: swift swiftui swiftui-list swiftui-navigationlink swiftui-navigationview