我可以从故事板实例化一个快速的自定义 UIView 而不嵌套在它自身内部吗?



每次我寻找如何使用笔尖制作自定义 UI 视图的地方,我都会看到以下代码可以使用

class CustomView: UIView {

var contentView: UIView!;
@IBOutlet weak var sampleLabel: UILabel!
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
if self.subviews.count == 0 {
nibSetup()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
if self.subviews.count == 0 {
nibSetup()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.subviews.count == 0 {
nibSetup()
}
}

fileprivate func nibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.translatesAutoresizingMaskIntoConstraints = true
addSubview(contentView)
}
fileprivate func loadViewFromNib() -> TimerView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}

但这基本上是将自定义视图的新实例(从笔尖加载(加载到原始实例上的 contentView 中。这一直有效,直到您想从视图所在的视图控制器调用视图上的方法。当您想从视图控制器在实例上调用方法时,您是在原始实例上调用该方法,而不是在 cotnentView 中的实例上调用该方法,因此结果是没有任何反应。

作为解决方法,我将内容视图声明为自定义视图而不是UIView,然后我的公共方法在内容视图上调用方法

class CustomView: UIView {

var contentView: CustomView!;
@IBOutlet weak var sampleLabel: UILabel!
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
if self.subviews.count == 0 {
nibSetup()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
if self.subviews.count == 0 {
nibSetup()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.subviews.count == 0 {
nibSetup()
}
}

fileprivate func nibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.translatesAutoresizingMaskIntoConstraints = true
addSubview(contentView)
}
fileprivate func loadViewFromNib() -> TimerView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! CustomView
return nibView
}
func setLabelText(blah: String) {
sampleLabel.text = blah
}
public func setLabelTextFromParent(words: String) {
contentView.setLabelText(blah: words)
}
}

不过,这似乎真的很笨拙。必须有更好的方法来做到这一点!

有人可以向我解释如何做到这一点,以便在从 IB 实例化自定义视图时,我只有一个自定义视图的实例,而不是嵌套在另一个实例中

。 谢谢。

您可以在UIView上定义一个扩展,例如

extension UIView {
class func fromNib<T : UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}

我在这里没有看到任何黑客。 称呼它为喜欢

let myCustomView: MyCustomView = UIView.fromNib()

最新更新