lmiguelvargasf lmiguelvargasf - 1 year ago 146
iOS Question

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download