lmiguelvargasf
lmiguelvargasf

Reputation: 69983

Swift: Add a xib into a UIView

I would like to add a custom UIView. The class definition of my custom view is:

class UserCoinView: UIView {
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var coinView: UIView!
    @IBOutlet weak var coinAmount: UILabel!
    @IBOutlet weak var coinIcon: UILabel!

    override func drawRect(rect: CGRect) {
        let smartCoins = SmartShopperUtil.getSmartShopper().smartCoins

        if smartCoins != nil && smartCoins >= 0  {
            coinAmount.text = String(smartCoins!)
            coinView.backgroundColor = SmartShopperUtil.getSmartCoinBackgroundColor(SmartShopperUtil.getSmartShopper().smartCoins!)
        }

        userName.text = SmartShopperUtil.getSmartShopperNameWithFullName(SmartShopperUtil.getSmartShopper().name)
        coinIcon.text = AEVIcons.AEV_SMART_COIN
    }
}

I have added a View in the ViewController I want to add this view, and I have set the custom class of this view as UserCoinView. After that, I have made a connection to the ViewController, and in this ViewController I have no idea what to do in order to display my custom UIView.

Thanks in advance for your help.

Upvotes: 2

Views: 20293

Answers (6)

dinesh sharma
dinesh sharma

Reputation: 617

You can also use generic function. For project use make it global

struct GenericFunctions {
static func addXIB<T>(xibName: String) -> T? {
        return  Bundle.main.loadNibNamed(xibName, owner: self, options: nil)?.first as? T
    }
}

Use this generic function like:-

if let cell: StudentStatusTableViewCell = GenericFunctions.addXIB(xibName: "StudentStatusTableViewCell") {

            return cell
        } else {
            return UITableViewCell()
        }

Benefit of generic is you can use this function for adding View, Tableviewcell and any other element. make sure you are using type in call like let cell: StudentStatusTableViewCell otherwise compiler won't infer the type.

Happy coding :)

Upvotes: 0

Rajkin Hossain
Rajkin Hossain

Reputation: 21

in Latest swift -> for example:

    let headerView = Bundle.main.loadNibNamed("SectionHeaderView", owner: 
    self, options: nil)?.first as? SectionHeaderView 
    self.view.addSubview(headerView!)
    headerView?.frame = CGRect(x:0, y: 0, width: view.frame.width, height: 50.0)

Upvotes: 2

Anit Kumar
Anit Kumar

Reputation: 8153

You can try This

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

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

func loadViewFromNib() {

let view = UINib(nibName: "CreditCardExperyView", bundle: NSBundle(forClass: self.dynamicType)).instantiateWithOwner(self, options: nil)[0] as! UIView

view.frame = bounds

view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

self.addSubview(view);

}

   // Call subview 
   let creditCardView : CreditCardExperyView = CreditCardExperyView(frame: CGRect(x: 0, y: UIScreen.mainScreen().bounds.size.height - 280, width: UIScreen.mainScreen().bounds.size.width, height: 280))

  selfView.addSubview(creditCardView)

Upvotes: 3

rkyr
rkyr

Reputation: 3251

There is couple of ways you can do this.

Add as subview programmatically.

If you use autolayout, better place for that is viewDidLayoutSubviews method.

var myCustomView: UserCoinView? // declare variable inside your controller
override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  if myCustomView == nil { // make it only once
    myCustomView = NSBundle.mainBundle().loadNibNamed("UserCoinView", owner: self, options: nil).first as? UserCoinView
    myCustomView.frame = ...
    self.view.addSubview(myCustomView) // you can omit 'self' here
    // if your app support both Portrait and Landscape orientations 
    // you should add constraints here
  }
}

Add as subview in InterfaceBuilder.

You simply need put an empty view to you controller inside the storyboard, and assign your class for this view in Identity Inspector. After that, you can drag-n-drop outlets to your controller classes if you need one.

enter image description here

As for me, I prefer the second method because you don't need to hardcode frame / create constraints programmatically, just add autolayout.

Upvotes: 16

Sonny
Sonny

Reputation: 21

I'm pretty new myself, but this should work.

Adding:

viewControllerName.addSubview(userCoinView)

Removing:

userCoinView.removeFromSuperview()

Upvotes: 1

Alexander
Alexander

Reputation: 149

Add it to a UIViewController's or UITableViewController's content view (or some other view in the view controller's view hierarchy) as a subview.

Upvotes: 2

Related Questions