我有一个UIView
子类,我希望在运行时从我的代码中实例化,它应该提供一个自定义选择器,使其范围(min,max)从服务器加载。
我正在寻找一种方法来调用单个方法:
* get the view from the Xib
* set its min, max properties so its can draw itself
我可以创建init(withMin:Int, max:Int)
但是视图不会从nib加载,因此永远不会调用awakeFromNib
(在那里有一些初始化代码)
感谢帮助者:)
答案 0 :(得分:1)
执行此操作的最佳方法是在子类
中创建static function
class SomeView: UIView {
var someInt: Int = 0
var someString: String = ""
static func instantiate(owner: AnyObject?, someInt: Int, someString: String) -> SomeView
// create the View
let newView = Bundle.main.loadNibNamed("SomeView", owner: self, options: nil)?.first as! SomeView
// set properties
newView.someString = someString
newView.someInt = someInt
return newView
}
...
some other codes here
...
}
使用这个就是这样。
let someView = SomeView.instantiate(owner: self, someInt: 100, someString: "LOOL")
self.view.addSubView(someView)