Swift: Add a xib into a UIView

2019-04-02 13:09发布

问题:

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.

回答1:

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.

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



回答2:

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.



回答3:

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)


回答4:

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)


回答5:

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

Adding:

viewControllerName.addSubview(userCoinView)

Removing:

userCoinView.removeFromSuperview()


标签: ios swift uiview