【问题标题】:Swift 3 set global variable valueSwift 3 设置全局变量值
【发布时间】:2017-01-17 09:52:21
【问题描述】:

所以我试图在加载视图控制器并设置它时获取一些数据,以便稍后在代码中使用它,但值不会更新。 CountData 值应该是代码底部的 3 但它不是

import UIKit
import Alamofire

class FooController: UIViewController, UITableViewDataSource {

    var CountData

    override func viewDidLoad() {

        super.viewDidLoad();

        Alamofire.request("http://foo:8080/joke.php").responseJSON{ response in
            if let JSON = response.result.value as? [String: String] {

            }
            //!!SET DATA HERE!!
            self.CountData = 3
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

         //!!USE IT HERE!!
          return CountData;
}

【问题讨论】:

  • self.CountData = 3 此行后再次重新加载 tableview

标签: ios iphone swift


【解决方案1】:

由于 Alamofire 请求是异步的,您需要为您的表调用 reloadData。

现在,你可以初始化你的

 var CountData = 3

当你得到响应时设置你想要的 CountData 然后调用

 self.CountData = 5    
 yourTableView.reloadData()

【讨论】:

  • 最好不要硬编码计数?当知道返回了多少数据时设置count,然后重新加载tableView
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多