我想知道是否有人可以解释为什么作为prepareForSegue()函数中目标ViewController的视图对象的出口被设置为nil。我只能猜测这意味着在调用PrepareForView时,这些对象尚未创建。虽然当你拥有目的地ViewController对象时,你是否有意义与之关联的视图对象出口也没有意义?我也知道直接修改另一个ViewController视图的值可能不是一个好习惯,但我只想更好地理解Swift 3的内部工作原理。谢谢!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ItemController"
{
let indexPath = tableView.indexPathForSelectedRow?.row
if let itemStruct = itemList[indexPath!] as ItemStruct?
{
let correspondingItemController : ItemController = segue.destination as! ItemController
if let textView = correspondingItemController.textView
{
print("This is not nil!") //this will NOT get hit. Why is this still nil??
}
correspondingItemController.itemStruct = itemStruct
}
}
}
答案 0 :(得分:3)
正如您在prepareForSegue
时所说的那样,尚未创建出口对象。 ViewController在访问view
属性时加载/创建其视图。当调用prepareForSegue
时,您的目标视图控制器将被实例化,但尚未加载其view
。您可以通过访问view
属性强制控制器从prepareForSegue加载其视图。
let correspondingItemController : ItemController = segue.destination as! ItemController
let _ = correspondingItemController.view // Forces controller to load its view.
现在您可以访问您的商店,但不建议这样做。一个好方法是在目标控制器中创建变量,从prepareForSegue
// prepareForSegue
correspondingItemController.name = "something"
// Destination controller
var name:String
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textView.text = name
}