[英]iOS: tableView.reloadData() doesn't work in swift
我正在嘗試在更新Swift中的數據后重新加載我的表視圖,但它似乎不起作用。 當我更改選項卡並返回時,表視圖會重新加載但不會自動重新加載。 這是我的代碼:
override func viewDidLoad() {
super.viewDidLoad()
// some code
refresh(self)
}
func refresh(sender: AnyObject) {
// Reload the data
self.tableView.reloadData()
}
我不明白為什么它在Objective-C中工作但在Swift中不起作用...我也嘗試過:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
因為我在其他帖子中看到了這個,但它也不起作用。
謝謝你的幫助
編輯:我的整個視圖控制器
class HighwaysViewController: UITableViewController {
var highways: [Highway]!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
highways = [Highway]()
// On ajoute le "Pull to refresh"
refreshControl = UIRefreshControl()
refreshControl!.addTarget(self, action: Selector("refresh:"), forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl!)
refresh(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refresh(sender: AnyObject) {
// Afficher l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
// On télécharge les autoroutes
var url = NSURL(string: "http://theurl.com")! // URL du JSON
var request = NSURLRequest(URL: url) // Création de la requête HTTP
var queue = NSOperationQueue() // Création de NSOperationQueue à laquelle le bloc du gestionnaire est distribué lorsque la demande complète ou échoué
// Envoi de la requête asynchrone en utilisant NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in
// Gestion des erreurs de connexion
if error != nil {
// Masquer l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
println(error.localizedDescription)
let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK")
errorAlert.show()
}
else {
// Récupération du JSON et gestion des erreurs
let json = JSON(data: data)
if let highwaysData = json.arrayValue {
for highway in highwaysData {
var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue)
self.highways.append(newHighway)
}
}
}
})
if (self.refreshControl!.refreshing) {
self.refreshControl!.endRefreshing()
}
tableView.reloadData() // Here is the problem
// Masquer l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return highways.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("highwayCell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
let tableCell = highways[indexPath.row]
let nameLabel = cell.viewWithTag(1) as UILabel
let directionLabel = cell.viewWithTag(2) as UILabel
nameLabel.text = tableCell.name!
directionLabel.text = tableCell.getDirections()
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
在refresh
函數中,您的加載使用閉包異步完成,但是您正在更新活動指示器並在閉包之外重新加載表,因此它將在加載完成之前執行。 您需要在閉包內移動此代碼並確保它在主隊列上執行(因為它更新了UI)
func refresh(sender: AnyObject) {
// Afficher l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
// On télécharge les autoroutes
var url = NSURL(string: "http://theurl.com")! // URL du JSON
var request = NSURLRequest(URL: url) // Création de la requête HTTP
var queue = NSOperationQueue() // Création de NSOperationQueue à laquelle le bloc du gestionnaire est distribué lorsque la demande complète ou échoué
// Envoi de la requête asynchrone en utilisant NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in
// Gestion des erreurs de connexion
if error != nil {
// Masquer l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
println(error.localizedDescription)
let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK")
errorAlert.show()
}
else {
// Récupération du JSON et gestion des erreurs
let json = JSON(data: data)
if let highwaysData = json.arrayValue {
for highway in highwaysData {
var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue)
self.highways.append(newHighway)
}
}
}
dispatch_async(dispatch_get_main_queue(), {
if (self.refreshControl!.refreshing) {
self.refreshControl!.endRefreshing()
}
self.tableView.reloadData()
// Masquer l'icône de chargement dans la barre de status
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
})
}
如果您正在使用標簽欄控制器(它聽起來像你),並且在修改另一個標簽中的內容后期望在表上刷新,則需要從目標視圖控制器的viewWillAppear內部調用tableView.reloadData() ()或viewDidAppear()方法。 viewDidLoad()僅在該視圖控制器的生命周期內調用一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.