简体   繁体   中英

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.

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.

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)

将它作为子视图添加到 UIViewController 或 UITableViewController 的内容视图(或视图控制器视图层次结构中的其他视图)。

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)

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

Adding:

viewControllerName.addSubview(userCoinView)

Removing:

userCoinView.removeFromSuperview()

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

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