【问题标题】:Notify table view to reload data通知表视图重新加载数据
【发布时间】:2015-01-11 07:34:34
【问题描述】:

我有这个表视图控制器:

class EventListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {

    // Event table view
    @IBOutlet weak var eventTableView: UITableView!

    var events: [Event] = []
    ...

我想从 Web 服务异步加载数据,这可能需要 5 秒。

我有这个异步代码:

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    // ApiClient is a custom wrapper for my API
    ApiClient.sharedInstance.getEvents({
        (error: NSError?, events: [Event]) in

        // All this runs within an asynchronous thread

        if let error = error {
            println("Error fetching events")
            println(error.localizedDescription)
        }

        self.events = events
        // How to notify the table view?
    })
    ...

数据加载正常,但表保持为空。一旦再次调用viewWillAppear(...),数据就在表中。

我需要通知表格视图吗?最干净的方法/最佳做法是什么?

谢谢!

【问题讨论】:

    标签: ios uitableview swift


    【解决方案1】:

    只需致电self.eventTableView.reloadData()

    如果您的闭包中的代码在异步线程上执行,您可能需要将该调用封装到 dispatch_async 调用中,以便在主线程上触发(因为所有与 UI 相关的工作必须始终在主线程):

    // All this runs within an asynchronous thread
    ...
    self.events = events
    
    // Notify the tableView to reload its data.
    // We ensure to execute that on the main queue/thread
    dispatch_async(dispatch_get_main_queue()) {
      self.eventTableView.reloadData()
    }
    

    【讨论】:

      【解决方案2】:

      要刷新调用 cellForRowAtIndexPath 的 tableView,您可以:

      self.eventTableView.reloadData()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-01
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多