简体   繁体   English

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

[英]View doesn't get updated until the second time loaded

I have a main view which is a table view with a list of countries. 我有一个主视图,它是带有国家列表的表格视图。 When clicking on any country name (cell), another view is loaded via segue which is passing the name of the country to the next view controller's navigation bar title. 单击任何国家名称(单元格)时,将通过segue加载另一个视图,该视图会将国家名称传递给下一个视图控制器的导航栏标题。

The problem is on the first click the title isn't updated, but when I click back button (dismissing the current view) and click on another country name, the second view loads again and shows the previous title that was suppose to be shown on the first attempt. 问题在于,第一次单击时标题未更新,但是当我单击“后退”按钮(关闭当前视图)并单击另一个国家/地区名称时,第二个视图再次加载并显示原本应该显示在上面的标题第一次尝试。

The code for the first main view controller: 第一个主视图控制器的代码:

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.
    }


}

the code for the second view controller: 第二个视图控制器的代码:

import UIKit

class CountryViewController: UIViewController {

    var passedValue:String!

    @IBOutlet weak var navBar: UINavigationBar!

    @IBAction func backButton(_ sender: AnyObject) {
        self.dismiss(animated: true, completion: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navBar.topItem?.title = passedValue
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

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

}

When you have a segue set up from a table view cell to a view controller in the storyboard then it is performed automatically when a cell is selected. 如果从表视图单元到情节提要中的视图控制器设置了segue,则在选择单元时会自动执行。 Your call to perform a segue in your cell selection method is performing the segue a second time after the first one has already been performed. 您在单元格选择方法中执行segue的调用是在第一次执行完之后第二次执行segue。

Remove your tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method and do all the data passing logic in prepareForSegue : 删除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
    }
}

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

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