在UIViewController中创建新的UIView(Creating new UIView in UIViewController)

编程入门 行业动态 更新时间:2024-10-19 08:57:46
在UIViewController中创建新的UIView(Creating new UIView in UIViewController)

我有一个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.

更多推荐

本文发布于:2023-08-04 13:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1416051.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:建新   中创   UIViewController   UIView   Creating

发布评论

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

>www.elefans.com

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