iOS:tableView.reloadData() 无法快速工作

2023-11-25

我试图在 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.
    }
    */

}

In your 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
            })

        })

    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS:tableView.reloadData() 无法快速工作 的相关文章

随机推荐

  • 子串索引范围

    Code public class Test public static void main String args String str University System out println str substring 4 7 Ou
  • 直接从 Java 调用 GWT RPC 服务

    有没有一种简单的方法可以直接从 Java 代码调用 GWT RPC 服务端点 我的意思是真正的 Java 代码 而不是编译成 javascript 的 Java 代码 我问这个问题是因为我们想要针对 GWT RPC 接口运行性能基准测试 压
  • WCF 服务未反序列化枚举值

    我构建了一个 WCF 服务 其中有一个部分如下所示 ServiceContract public class Service OperationContract public SomethingElse Method Code a para
  • FlatList 组件生命周期方法 ScrollToIndex ScrollToEnd 等

    我正在使用新的FlatList成分并想利用ScrollToIndex or ScrollToEnd 在生命周期方法中 例如componentDidMount 我有一个包含 100 个项目的数组 我不想从第一个项目开始渲染 而是从一开始就开始
  • 连接错误:“没有到主机的路由”

    我正在编写一个基于 AX 25 协议的服务器 客户端 C 程序 服务器创建套接字 绑定成功并侦听即将到来的连接 客户端在不同的线程中运行 但连接失败 并显示 没有到主机的路由 服务器代码 include
  • Grails - 为每个响应添加标头

    我怎样才能添加响应头 比如X Time看起来像这样 X Time 112 其中给出的值是处理响应所需的时间 以毫秒为单位 有没有一种非常简单的方法可以将其添加到 Grails 应用程序中 我不想永久保留它 但在开发我的应用程序时保留它会很高
  • 将 ggplot2 与名称中包含空格的列一起使用

    我有以下数据帧结构 df lt as data frame A colnames df lt c Sum of MAE Company df lt na omit df df2 lt df order df 1 df2 lt head df
  • 我怎样才能每一秒都做某事? [LibGDX]

    假设我想制作一个循环或每秒打印出的内容 例如 马里奥 我怎样才能做到这一点 似乎无法在任何地方找到任何好的教程来教授这个 P 正如 BennX所说 你可以总结一下delta渲染方法中的时间或通过调用获取它Gdx graphics getDe
  • 显式使用“new EventHandler”声明有好处吗?

    将事件处理程序分配给上下文之类的东西MenuItem 例如 有两种可接受的语法 MenuItem item new MenuItem Open Image btnOpenImage Click 和 MenuItem item new Men
  • MinGW中有fmemopen()吗

    我正在尝试编译一些使用fmemopenMinGW 中的函数 我发现MinGW没有这个功能 我需要一个相当于fmemopen 我可以使用其他功能吗 由于内核中缺少功能 win32 上没有 fmemopen 等效项 我认为 cygwin 使用如
  • 无法解析符号 DaggerApplicationComponent

    我将 Dagger2 与 java 一起使用 并收到 无法解析应用程序中的符号 DaggerApplicationComponent 错误 依赖关系似乎有问题 任何帮助将非常感激 我的完整代码在这里 https github com roh
  • 如何强制 to_yaml 以文字块样式输出长字符串?

    我在哈希中有很长的字符串值 我想以文字块样式打印 以 gt or 在 YAML 中 而不是作为内联字符串 有没有办法在调用时强制执行此操作 to yaml 文字块样式的示例 this Foo Bar None
  • 错误:无法将 typeid 与 -fno-rtti 一起使用

    当我尝试编译我的项目时 我收到此消息 Cannot use typeid with fno rtti 我正在使用 opencv 框架 我用谷歌搜索了这个问题 但是 我在互联网上发现的错误似乎与我的问题无关 我不知道问题是否与包含 代码或编译
  • Qt:Qt 类与标准 C++

    标准 c 和 Qt 之间存在大量重复功能 在某些时候 这似乎合乎逻辑 但很多时候却显得愚蠢 就像我想尝试一种新的编程语言 学习我已经知道的东西 例如使用 QFile 另外 如果我全部用 Qt 方式完成 并且假设现在我想移出 Qt 框架 那么
  • SQLAlchemy,获取未绑定到会话的对象

    我试图从数据库中获取对象集合并将其传递给未连接到数据库的另一个进程 我的代码如下所示 但我不断收到 sqlalchemy exc UnboundExecutionError Instance
  • 控件中的嵌入表单或作为用户控件的表单

    好吧 我有一个大型 CRUD 应用程序 它使用嵌入了表单的选项卡 如下所示 gt public static void ShowFormInContainerControl Control ctl Form frm frm TopLevel
  • 在 DocumentDB 上使用 Any 进行子集合的 LINQ 查询问题

    使用 v1 8 Net SDK 尝试返回 Sales 其中 Sales 客户端数组包含我正在查找的客户端 ID Sales Where sale gt sale Clients Any c gt c ClientId clientID 返回
  • 同步特征是发送特征的严格子集吗?什么实现了不发送同步?

    In Rust 编程 第二版 作者 吉姆 布兰迪 杰森 奥伦多夫 利奥诺拉 F S 廷德尔第 520 页上有一个图表 显示发送和同步 并带有重叠的圆圈 其中同步完全包含在发送中 这让我相信所有实现同步的东西也必须实现发送 但是第 561 页
  • 为什么我不应该从构造函数中调用我的依赖项?

    长期以来 我一直认为从构造函数中调用类依赖项是一种不好的做法 但昨天无法向同事阐明原因 谁能提供一个不这样做的充分理由 尼古拉 马洛维奇的原因有几个国际奥委会第四定律 当我们使用构造函数注入编写应用程序时 我们经常创建大量的对象图 并且我们
  • iOS:tableView.reloadData() 无法快速工作

    我试图在 Swift 中更新数据后重新加载表视图 但它似乎不起作用 当我更改选项卡并返回时 表视图会重新加载 但不会自动加载 这是我的代码 override func viewDidLoad super viewDidLoad some c