将UIView子类链接到xib文件

时间:2015-09-20 13:20:02

标签: ios swift uiview

我创建了一个UIView子类,我希望将其链接到xib文件。我已经添加了一个xib文件并将该类设置为DraggableView,但是当我例如创建一个标签并将其链接到information时。它返回information等于零?为什么它不起作用?

class DraggableView: UIView {
    var delegate: DraggableViewDelegate!
    @IBOutlet var information: UILabel!


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        information.text = "no info given"
        information.textAlignment = NSTextAlignment.Center
        information.textColor = UIColor.blackColor()

        self.backgroundColor = UIColor.whiteColor()



    }
}

2 个答案:

答案 0 :(得分:0)

请确保在自定义UIView中添加来自XIB方法的init,如下所示:

class func instanceFromNib() -> UIView {
        return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
    }

然后你可以像这样使用它:

var view = DraggableView.instanceFromNib()
view.information.text = "Test Label"
self.view.addSubview(view)

答案 1 :(得分:0)

在设置对象值之前,您需要自定义UIView首先加载XIB文件。

 class DraggableView: UIView {

     var delegate: DraggableViewDelegate!
     @IBOutlet var information: UILabel!

    init() { xibSetup() }

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        if self.subviews.count == 0 {
            xibSetup()
        }
    }


    func xibSetup() {
        let view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        addSubview(view)


        // INIT THERE YOUR LABEL
        information.text = "no info given"
        information.textAlignment = NSTextAlignment.Center
        information.textColor = UIColor.blackColor()

       self.backgroundColor = UIColor.whiteColor()
    }

    func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "nib file name", bundle: bundle)

        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        return view
    }

并简单地打电话:

var view = DraggableView()