问题描述
我目前正在快速学习,我正在尝试从故事板作品中学习实例化,但我现在面临的错误并没有太多记录.
I'm currently learning swift and I'm trying to learn of instanciation from storyboard works, but the error I'm facing now isn't documented very much.
我在主故事板中创建了一个视图控制器,并将其类型指定为我之前调用的自定义类SimpleNewsViewController,这是我的类的代码,它不是复杂:
I created a viewcontroller in my main storyboard and I specified it's type as a custom class I called previously SimpleNewsViewController, here's the code of my class, it is'nt complicated:
class SimpleNewsViewController: UIViewController {
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!
var event: Events!
override func viewDidLoad() {
super.viewDidLoad()
}
}
在我的主故事板上,这里是我指定的自定义 ViewController:我的故事板实现
On my main storyboard here is the custom ViewController I specified :My Storyboard implementation
现在问题来了:在我的代码中,我实例化了我的 ViewController 多亏了 instanciateViewController(identifier: "NewsView") 然后我尝试像这段代码一样设置我的 3 个属性:
Now here's the problem : In my code I instanciate my ViewController thanks to the instanciateViewController(identifier: "NewsView") and then I try to set my 3 attributes like in this piece of code :
...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
//controller.myImage.image = UIImage(named: "image.jpg")
//controller.myText.text = "this is an example that can be really long"
//controller.myTitle.text = "this is a title example
self.navigationController?.pushViewController(controller, animated: true)
...
如果我取消对三行的注释,则会出现错误提示:
If I un-comment the three lines I have an error saying:
致命错误:在展开可选值时意外发现 nil
IDE 还会显示错误代码和线程(如果有帮助的话):错误
The IDE also displays the error code and the thread (if that can help):The error
推荐答案
在实例化控制器后,outlet 还没有连接,你必须在viewDidLoad()
Right after instantiating the controller the outlets are not connected yet, you have to declare temporary variables and set the outlet properties in viewDidLoad()
...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
controller.tempImage = UIImage(named: "image.jpg")
controller.tempLabel = "this is an example that can be really long"
controller.tempText = "this is a title example
self.navigationController?.pushViewController(controller, animated: true)
...
class SimpleNewsViewController: UIViewController {
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!
var tempImage : UIImage?
var tempLabel = ""
var tempText = ""
var event: Events!
override func viewDidLoad() {
super.viewDidLoad()
myImage.image = tempImage
myLabel.text = tempLabel
tempText.text = tempText
}
这篇关于获取使用故事板创建的视图控制器的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!