我有一个模型课:
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文件,以及一个带有网点和func的快捷类,以返回其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)
}
}
我无法解决的问题是如何更改实例化的笔尖标签? 我在stackOverflow上阅读了许多答案,但是找不到清晰的答案。
连接nib-itsClass-customModel的最佳方法是什么?
答案 0 :(得分:1)
更改此行
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)