当前,我具有以下便捷的通用函数,该函数使我能够从XIB创建自定义视图
extension UIView {
static func instanceFromNib<T: UIView>() -> T {
return UINib(nibName: String(describing: self), bundle: nil).instantiate(withOwner: self, options: nil)[0] as! T
}
}
用法是
let colorPickerView: ColorPickerView
// Returned type from ColorPickerView.instanceFromNib is UIView, not ColorPickerView.
colorPickerView = ColorPickerView.instanceFromNib()
但是,编译器只能从ColorPickerView.instanceFromNib
is知道返回值UIView
。它不知道返回值的ColorPickerView.instanceFromNib
其实ColorPickerView
。
以下代码将毫无问题地进行编译,但会导致运行时错误。
let colorPickerView: UIButton // UIButton is child of UIView.
// Returned type from ColorPickerView.instanceFromNib is UIView, not ColorPickerView.
colorPickerView = ColorPickerView.instanceFromNib()
我想知道,是否有办法进一步改善上述通用功能,以便我们能够
// No issue. Returned type from CustomView1.instanceFromNib is CustomView1.
let customView1: CustomView1 = CustomView1.instanceFromNib()
// No issue. Returned type from CustomView2.instanceFromNib is CustomView2.
let customView2: CustomView2 = CustomView2.instanceFromNib()
// Compile error. Compiler knows the returned type is CustomView1.
let customView3: CustomView3 = CustomView1.instanceFromNib()
您可以改进它,使上面的代码失败,但是永远不能确定它的类型正确。
要处理上面的代码,您只需更改instanceFromNib()
为返回Self,而不是“无论键入呼叫者请求的内容”。
static func instanceFromNib() -> Self {
UINib(nibName: String(describing: self), bundle: nil)
.instantiate(withOwner: self, options: nil)[0] as! Self
}
但是该NIB仍可能持有错误的类型,并且只有在运行时才会发现该错误,因为您必须从文件中加载数据才能知道。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句