实例化 Nib 并访问其子视图

Instantiate Nib and access its SubViews

我有一个模型class:

import UIKit

class MyModel: NSObject
{
   var str1 : String = "Test String 1"
   var str2 : String = "Test String 2"
   var str3 : String = "Test String 3"
}

我有一个带有 3 个标签的 nib 文件和一个 swift class 带有出口和功能到 return 它的 nib :

import UIKit

class MyNibClass: UIView
{
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!

    func instanceMyNib() -> UIView
    {
        let view =  UINib(nibName: "myNib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
        return view
    }
}

在我的 viewController 中,我使用此代码来实例化我的笔尖并将其添加到 viewController 查看

import UIKit

class myViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
        let model : MyModel = MyModel()
        let nibClass : MyNibClass = MyNibClass()
        let viewFromNib = nibClass.instanceMyNib()
        view.addSubview(viewFromNib)
    }
}

我无法解决的问题是如何更改实例化的笔尖标签? 我在 Whosebug 上阅读了很多答案,但找不到明确的答案。

连接 nib-itsClass-customModel 的最佳方式是什么?

更改此行

let view =  UINib(nibName: "myNib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView

let view =  UINib(nibName: "myNib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! MyNibClass

那么在添加自定义视图之前,您可以

let viewFromNib = nibClass.instanceMyNib()
viewFromNib.label1.text = "anyThing"
view.addSubview(viewFromNib)