简体   繁体   中英

Link a UIView subclass to xib file

I've created a UIView subclass, which i want to link to a xib file. I've added a xib file and set the class to DraggableView, however when i for instance create a lable and link it to the information . it returns that information is equal to nil? why doesnt it work?

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()



    }
}

Please ensure you add init from XIB method in your custom UIView like this:

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

And then you can use it like this:

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

You need for your custom UIView to load XIB file first before setting objects value.

 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
    }

and call simplely like that :

var view = DraggableView()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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