在第二次加载之前,View不会更新

时间:2016-09-01 22:04:17

标签: ios swift uiviewcontroller

我有一个主视图,它是一个包含国家列表的表格视图。单击任何国家/地区名称(单元格)时,将通过segue加载另一个视图,该视图将国家/地区名称传递给下一个视图控制器的导航栏标题。

第一次点击时问题是标题没有更新,但是当我点击后退按钮(取消当前视图)并点击另一个国家/地区名称时,第二个视图再次加载并显示以前的标题在第一次尝试时显示。

第一个主视图控制器的代码:

div

第二个视图控制器的代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var sectionsArray = [String]()
    var sectionsCountries = [Array<AnyObject>]()

    @IBOutlet weak var countries: UITableView!

    internal func numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections.
        return self.sectionsArray.count
    }

    internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
            return self.sectionsCountries[section].count
    }

    internal func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionsArray[section]
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath)
        cell.textLabel?.text = self.sectionsCountries[indexPath.section][indexPath.row] as? String
        return cell
    }

    var valueToPass:String!

    internal func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.row)!")

        // Get Cell Label
        let indexPath = tableView.indexPathForSelectedRow;
        let currentCell = tableView.cellForRow(at: indexPath!) as UITableViewCell!;

        valueToPass = currentCell?.textLabel?.text
        performSegue(withIdentifier: "cellSegue", sender: self)
        //print(valueToPass)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "cellSegue" {
            let destination = segue.destination as! CountryViewController
            destination.passedValue = valueToPass
        }
    }

    override func viewDidLoad() {

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = URL(string: "http://cyber7.co.il/swift/countries/countries-list.json")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error)
            } else {
                if let urlContent = data {
                    do {
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                        for result in jsonResult as! [Dictionary<String, AnyObject>]{
                            self.sectionsArray.append(result["sectionName"] as! String)
                            self.sectionsCountries.append(result["sectionCountries"] as! Array<String> as [AnyObject])
                        }
                    } catch {
                        print("JSON Processing Failed")
                    }
                    DispatchQueue.main.async(execute: { () -> Void in
                        self.countries.reloadData()
                    })
                }
            }
        }
        task.resume()
    }

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


}

1 个答案:

答案 0 :(得分:0)

当您从表格视图单元格设置segue到故事板中的视图控制器时,会在选择单元格时自动执行。您在单元格选择方法中执行segue的调用是在第一次执行segue后第二次执行segue。

删除tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)方法并执行prepareForSegue中的所有数据传递逻辑:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "cellSegue" {
        let destination = segue.destination as! CountryViewController
        let indexPath = countries.indexPathForSelectedRow
        let currentCell = countries.cellForRow(at: indexPath!)
        destination.passedValue = currentCell?.textLabel?.text
    }
}