繁体   English   中英

将Xib加载到UIView中而不将其添加为子视图

[英]Load Xib into UIView without add it as a subview

如何将笔尖加载到UIView而不必将其添加为subview 在objc中,您可以在init方法中完成self = [NSBundle MainBundle].loadNibNamed…但是swift表示“Cannot assign to 'self' in a method”

在此处输入图片说明

在对象中,您可以执行此操作。 可重用的视图,但是似乎并不喜欢它。 我发现的唯一方法是将Xib加载到UIView并将其添加为当前视图的子视图

@IBDesignable class CustomViewFromXib: UIView 
{
    var nibName: String = "CustomViewFromXib"
    override init(frame: CGRect) 
    {
        super.init(frame: frame)
        setup()
    }
    required init(coder aDecoder: NSCoder) 
    {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() 
    {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        view.frame = bounds
        self.view.addSubview(view)
    }
}

[[NSBundle mainBundle] loadNibNamed:@“ myNib” owner:self options:nil];

是另一种方法并设置其所有者。

有点滑,可能会破坏KVO / KVC的一面

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM