Load custom xib from viewcontroller in SWIFT

In custom UIView class  class NearByOffer: UIView, override the init method as follows


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

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

 }


Set up the xib as follows:-

func xibSetup() {
        view = loadViewFromNib()
        
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]        
        // Adding custom subview on top of our view (over any custom drawing > see note below)
        view.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
        addSubview(view)
    }


Load view from custom nib/xib as follows:-
    func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: "NearByOffer", bundle: bundle)
        
        // Assumes UIView is top level and only object in CustomView.xib file
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        return view
    }



USAGE in ViewController

    func showNearByOfferPopup()
    {
        let window = UIApplication.sharedApplication().delegate?.window
        let nearByOfferViewObject = NearByOffer(frame: (window!?.frame)!)
        window!!.addSubview(nearByOfferViewObject)
    }

Comments

Popular posts from this blog

Vector graphics in iOS

Exception Handling - Objective C

How to show activity indicator in watch kit