繁体   English   中英

迅速:完成处理程序

[英]swift: Completion handler

所以,我有方法loadData()parse.com下载数据

在此处输入图片说明

我应该展示所有以表格视图显示的图像。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) as! LeaguesTableViewCell

    loadData { (success) in
        if success {
            cell.leagueImage.image = UIImage(data: self.leaguesImage[indexPath.row])
            cell.leagueNameLabel.text = self.leagues[indexPath.row]["name"] as? String
        } else {
            cell.leagueNameLabel.text = "Wait"
        }
    }


    return cell

}

它没有用。 我在viewDidLoad()调用函数,但它也不正确,表视图为空。

在此处输入图片说明 因为我的数组是空的

我的

将数据加载到UITableView的基本过程是:

  1. 加载数据
  2. 重新加载表格视图
  3. 返回numberOfSectionsInTableView:的节数numberOfSectionsInTableView:方法:在您的情况下,只有1个节。
  4. 返回tableView:numberOfRowsInSection:的行数:在您的情况下,如果已加载数据,则返回联赛数。 如果未加载数据,则返回1,以便表视图至少具有一行以显示“等待”消息。
  5. 创建并填充从数据的单元格:用leaguesleaguesImage

例:

private var loaded = false   

override func viewDidLoad() {
    super.viewDidLoad()

    loaded = false

    loadData() { success in
        NSOperationQueue.mainQueue().addOperationWithBlock() {
            self.loaded = success
            self.tableView.reloadData()
        }
    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection: Int) -> Int {
    if loaded {
        return leagues.count 
    }
    else {
        return 1
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) as! LeaguesTableViewCell

    if loaded {
        cell.leagueImage.image = UIImage(data: self.leaguesImage[indexPath.row])
        cell.leagueNameLabel.text = self.leagues[indexPath.row]["name"] as? String
    }
    else {
        cell.leagueNameLabel.text = "Wait"
    }

    return cell
}

尝试先设置委托和数据源。 如果您有视图控制器以外的其他数据源,请保留它,否则您将不会获得任何回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM