【发布时间】:2026-02-06 19:40:01
【问题描述】:
我正在使用 Swift 在 iOS 上进行下拉刷新。
我有一个包含城市名称的数组,cityNames = ["Chicago", "New York City"]
我实现了一个下拉刷新来从互联网上获取温度数据。所以每次我触发下拉刷新时,它都会上网并获取cityNames数组中每个城市的温度。
这是拉动刷新的代码
var weatherDetail = [Weather]()
// Pull to refresh
func refreshData() {
var cityNames = [String]()
for (index, _) in weatherDetail.enumerate() {
let info = weatherDetail[index]
cityNames.append(info.cityName)
}
print(cityNames)
weatherDetail.removeAll()
for city in cityNames {
self.forwardGeocoding(city)
}
weatherCityTable.reloadData()
refreshControl.endRefreshing()
}
在上面的代码中,weatherDetail 是一个模型数组(我不知道如何表达这个,但Weather 是一个模型,其中包含城市名称、温度、日出时间、高/低温.forwardGeocoding 是一个获取城市地理坐标的函数,然后发送请求以获取该城市的天气数据。
拉动刷新工作,我遇到的问题是,在我拉动的前 2,3 次,它没有问题。但是当我拉更多次时,数组会突然变为cityNames = ["Chicago", "Chicago"]
感谢您的帮助,如果您需要更多信息,请告诉我。
更新:
我删除了weatherDetail.removeAll(),尝试将相同的数据附加到数组中。刷新后,打印出"Chicago", "New York City", "Chicago", "Chicago"。如果我刷新它更多次,它会打印出类似"Chicago", "New York City", "Chicago", "Chicago", "Chicago", "Chicago"
【问题讨论】:
-
cityNames 数组不在您的代码中。怎么填的?
-
@Darko 谢谢指出,刚刚修改了代码。
-
从给定的代码中可以看到一个问题:您只是附加到 cityNames 但永远不会删除它。
-
也许您在刷新时尝试刷新?所以,也许添加一个 var isRefreshing 并且如果它没有更新就更新。
-
weatherDetail 数组中填充了什么?
标签: ios arrays swift uitableview pull-to-refresh