初始化viewcontroller时传递变量(passing variable when viewcontroller is initialized)

编程入门 行业动态 更新时间:2024-10-14 08:29:06
初始化viewcontroller时传递变量(passing variable when viewcontroller is initialized)

点击按钮时我有一个方法运行:

let tempVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AwardViewController") as! AwardViewController tempVC.currentDocumentPartTitle = currentDocumentPart.title

这里是AwardViewController类,

class AwardViewController: UIViewController { @IBOutlet weak var textView: UITextView! var currentDocumentPartTitle: String! override func awakeFromNib() { super.awakeFromNib() //assigning text to UITextView in awakeFromNib method //In order to find right textfile, currentDocumentPartTitle is used to search right data in plist. }

问题是,即使我传递变量,它在awakeFromNib方法中返回nil值错误,说currentDocumentPartTitle为nil。 如何在调用awakeFromNib之前传递变量?

I have a method running when a button is tapped:

let tempVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AwardViewController") as! AwardViewController tempVC.currentDocumentPartTitle = currentDocumentPart.title

And here is AwardViewController class,

class AwardViewController: UIViewController { @IBOutlet weak var textView: UITextView! var currentDocumentPartTitle: String! override func awakeFromNib() { super.awakeFromNib() //assigning text to UITextView in awakeFromNib method //In order to find right textfile, currentDocumentPartTitle is used to search right data in plist. }

The problem is that even if I pass the variable, it returns nil value error in awakeFromNib method saying currentDocumentPartTitle is nil. How do I pass a variable before awakeFromNib is called?

最满意答案

发生这种情况是因为在视图的属性可分配之前执行了awakeFromNib() 。 请参阅https://stackoverflow.com/a/377390/1214800 。

为什么不在viewDidLoad()简单地做你需要做的事情?

override func viewDidLoad() { super.viewDidLoad() print(currentDocumentPartTitle!) // works! }

This happens because awakeFromNib() is performed before the view's properties are allocatable. See https://stackoverflow.com/a/377390/1214800.

Why not simply do what you need to do inside of viewDidLoad()?

override func viewDidLoad() { super.viewDidLoad() print(currentDocumentPartTitle!) // works! }

更多推荐

本文发布于:2023-07-17 13:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   变量   viewcontroller   initialized   passing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!