【发布时间】:2020-08-30 04:41:06
【问题描述】:
所以我的所有控制器都是以编程方式完成的,以避免出现转场和那种复杂的事情。
我有一个从网络下载数据的视图控制器(称之为 ProfileViewController)。
所以我在 ProfileViewController 中有一个方法,该方法使用静态 tableview 实例化单个故事板文件,其中包含文本字段的单元格。方法如下:
ProfileViewController:
func userSelectedUpdateProfile() {
// Obtain reference to the only storyboard file named EditProfileSB
let storyboard = UIStoryboard(name: "EditProfileSB", bundle: nil)
// Since the Tableview is embedded in a navigation controller (with ID set to "navigationID")
if let parentNavigationController = storyboard.instantiateViewController(withIdentifier: "navigationID") as? UINavigationController {
// Now find the embedded TableViewController and access it's properties to pass to.
if let childEditController = parentNavigationController.topViewController as? EditProfileTableViewController {
// ! Error here ! Found nil when doing this.
childEditController.nameTextfield.text = "Passed this to static cell"
}
present(parentNavigationController, animated: true, completion: nil)
}
}
所以代码本身对我在这里想要实现的目标是不言自明的。 TableView 嵌入在导航中(在情节提要上使用“Editor > Embed In”完成),因此在第二个嵌套的if let 语句中,我现在正在检查以查找 Edit 控制器并访问其属性(nameTextfield)。
当我尝试访问 nameTextField.text 属性时发生崩溃。此文本字段是使用情节提要设置的。这是 EditProfileTableViewController:
class EditProfileTableViewController: UITableViewController {
@IBOutlet weak var nameTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
// Other methods ...
}
我在这里遗漏了什么吗?我在 childEditController.nameTextfield.text = "Passed this to static cell" 方法 userSelectedUpdateProfile() 上不断崩溃。
【问题讨论】:
-
很可能是 nameTextfield 为 nil,解决方案将在 EditProfileTableViewController 上添加变量“var name : String = "" " 和 childEditController。 name = "Passed this to static cell" 所以最后在 EditProfileTableViewController 的 viewdidload 中添加 nameTextfield.text = name.
-
谢谢伙计,这成功了。
-
出现这种情况是因为你尝试使用 nameTextField 时 this 为 nil,请尝试阅读 ViewController 的生命周期
标签: ios swift storyboard segue uistoryboardsegue