IOS 9 TableViewCell在选定之前不可见

时间:2016-05-06 16:19:10

标签: uitableview swift2 nsurlsession nsmutableurlrequest

我在后台线程中使用服务来获取发布请求。然后我使用NSJSONSerialization将其转换为数组。我循环遍历数组以创建一个团队阵列。然后我回到主队列并调用完成处理程序。

小组:

class Team
{
    private (set) var id: Int
    private (set) var city: String
    private (set) var name: String
    private (set) var abbreviation: String

    init(data: JSONDictionary)
    {
        id = data["team_id"] as? Int ?? 0
        city = data["city"] as? String ?? ""
        name = data["team_name"] as? String ?? ""
        abbreviation = data["abbreviation"] as? String ?? ""
    }


}

服务:

func getTeams(urlString: String, completion: [Team] -> Void)
{
    let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let url = NSURL(string: urlString)!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"

    let task = session.dataTaskWithRequest(request) {
        (data, response, error) in

        if error != nil {
            print(error!.localizedDescription)
        } else {
            print(data)
            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? JSONArray {

                    var teams = [Team]()

                    for team in json {
                        let team = Team(data: team as! JSONDictionary)
                        teams.append(team)
                    }
                    let priority = DISPATCH_QUEUE_PRIORITY_HIGH
                    dispatch_async(dispatch_get_global_queue(priority, 0)) {
                        dispatch_async(dispatch_get_main_queue()) {
                            completion(teams)
                        }
                    }
                }
            } catch {
                print("error in NSJSONSerialization")
            }
        }
    }

    task.resume()
} 
然后我尝试使用数据来填充tableView。我也成功地循环并将所有团队名称打印到控制台。我遇到的问题它填充tableView但一切都是白色的。在我触摸它之前,我无法看到标签上的任何文本。选择表格单元格时,我可以看到黑色标签的内容。但如果我触摸另一个,则只显示当前选择的标签。一旦数据加载,它们似乎都应该显示出来。

自定义单元格:

class TeamTableViewCell: UITableViewCell {

    var team: Team? {
        didSet {
            updateCell()
        }
    }

    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var abbreviation: UILabel!

    func updateCell()
    {
        title.text = team?.name ?? ""
        abbreviation.text = team?.abbreviation ?? ""
    }
}

控制器:

var teams = [Team]()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Teams"
        let service = NBAService()
        service.getTeams("https://probasketballapi.com/teams?api_key=\(Constants.API.APIKey)", completion: didLoadTeams )
    }

    func didLoadTeams(teams: [Team])
    {
        self.teams = teams
        tableView.reloadData()

        // This actuall works returns an list of team names to the console.
        for team in teams {
            print("Team: \(team.name)")
        }

    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return teams.count
    }

    struct Storyboard {
        static let TeamCell = "TeamCell"
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TeamCell, forIndexPath: indexPath) as! TeamTableViewCell

        // Configure the cell...
        cell.team = self.teams[indexPath.row]

        return cell
    }

当我将团队名称打印到控制台打印正常时,我知道我已成功从请求中获取数据。选择单元格时,一次可以看到一个团队。我缺少什么

1 个答案:

答案 0 :(得分:0)

这有点奇怪:

dispatch_async(dispatch_get_global_queue(priority, 0)) {
  dispatch_async(dispatch_get_main_queue()) {
    completion(teams)
  }
}

我会将其替换为:

dispatch_async(dispatch_get_main_queue()) {
  completion(teams)
}