我只能加载一次视图控制器吗?

时间:2018-07-26 21:28:26

标签: ios swift segue navigationcontroller pass-data

我用城市清单制作了表格视图。当我选择一个城市单元格时,它将传递城市名称并通过在情节提要中使用segue显示城市的天气预报。但是,每次看起来都会创建一个新的viewcontroller。但是我不希望这样发生。我希望它只能加载一次。对于用户来说,当他们没有互联网时,他们仍然可以看到数据,我为他们提供了一个刷新数据的按钮。 这是我的代码:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showCurrentWeather", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showCurrentWeather"{
        let dvc = segue.destination as? WeatherViewController
        let selectedIndexPath = self.tableView.indexPathForSelectedRow
        if let selectedRow = selectedIndexPath?.row{
            dvc?.infoFromViewOne=cityName[selectedRow]

        }
    }

我尝试使用导航控制器来推动viewcontroller,

   weatherViewController=self.storyboard?.instantiateViewController(withIdentifier: "weatherViewController") as! UIViewController

self.navigationController?.pushViewController(weatherViewController!, animated: true)

在weatherViewController中,我做了一个自定义的后退按钮以弹出视图控制器,

    @objc func backAction(){

    navigationController?.popViewController(animated: true)
}

但是,使用导航控制器时,我不知道如何将城市名称从所选单元格传递到天气视图控制器。 我该如何解决该问题?谢谢

1 个答案:

答案 0 :(得分:1)

您需要强制转换as! WeatherViewController而不是as! UIViewController,因为它的默认返回值是可选的UIViewController

weatherViewController = self.storyboard?.instantiateViewController(withIdentifier: "weatherViewController")    as! WeatherViewController
weatherViewController.infoFromViewOne = cityName[indexPath.row]
self.navigationController?.pushViewController(weatherViewController, animated: true)

在不可见的情况下将VC保留在内存中并不是一个好主意,因为它必须遵循create / deinit

相关问题