我有一个ViewController ,我用它来加载UIView( TempView )作为子视图。
tempView = TempView(frame: CGRectMake(10, 10, view.frame.size.width, view.frame.size.height)) tempView.tempLabelText = "YAY" view.addSubview(tempView)tempView有一个变量和一个@IBOutlet 。
var tempLabelText : String? @IBOutlet weak var tempLabel: UILabel!我在TempView类的awakeFromNib()中添加了一个语句print(tempLabelText) ,其打印为nil
我希望能够从ViewController将值更改为tempLabelText ,所以当我添加子视图时,标签会显示我声明的内容。 我错过了什么?
我项目中的文件:
1. ViewController - 创建tempView:TempView!
2. TempView.swift - UIView类
3. tempView.xib - tempView.xib ,里面有一个标签。 连接到TempView.swift的标签出口。
I have a ViewController which I use to load a UIView (TempView) as a subview from.
tempView = TempView(frame: CGRectMake(10, 10, view.frame.size.width, view.frame.size.height)) tempView.tempLabelText = "YAY" view.addSubview(tempView)tempView has one variable and one @IBOutlet.
var tempLabelText : String? @IBOutlet weak var tempLabel: UILabel!I added a statement print(tempLabelText) inside awakeFromNib() of the TempView class and its prints nil
I want to be able to change the value to tempLabelText from ViewController so when I add the subview, The label is shown with what I declared. What am I missing?
Files in my project:
1.ViewController - Creates tempView : TempView!
2.TempView.swift - UIView class
3.tempView.xib - .xib with one label inside. Outlet of label connected to TempView.swift.
最满意答案
在此处初始化视图时会调用awakeFromNib()方法:
tempView = TempView(frame: CGRectMake(10, 10, view.frame.size.width, view.frame.size.height))此时变量tempLabelText尚未初始化。 您只在下一行为此变量赋值。
awakeFromNib() method is called when you initialize your view here:
tempView = TempView(frame: CGRectMake(10, 10, view.frame.size.width, view.frame.size.height))At this moment variable tempLabelText isn't initialized yet. You assign value to this variable only on the next line.
更多推荐
发布评论