0

I need to create custom xib uiview programatically

Here i dont want to add any view in owner viewcontroller to give its class name as ReusableContainerview and show that... because i have around 30 viewcontrollers so i cant add view in all my 30 viewcontrollers

i just want to show custom view in my homevc without adding uiview in storybard but how to call programatically in homevc to show custom view.. please guide me

code: code for creating custom view, to use in all my screens

import UIKit
class ReusableContainerview: UIView {

@IBOutlet weak var containerView: UIView!
override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
}

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

func commonInit(){
    var viewFromXib = Bundle.main.loadNibNamed("ReusableContainerview", owner: self, options: nil)![0] as! UIView
    viewFromXib.frame = self.bounds
    viewFromXib = ReusableContainerview(frame: CGRect(x: 0, y: 0, width: bounds.width * 0.9, height: 300))
    addSubview(viewFromXib)
}
}

for eg i would like to call custom view like this in my home page but in my home screen i am not getting reuseView.. how to show reuseView in home without adding uiview in storyboard.. please guide me

import UIKit

var reuseView: ReusableContainerview?
class HomeVC: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    reuseView?.isHidden = false
}
}
Swift
  • 1,074
  • 12
  • 46
  • You first need to initialize reuseView and add it to the view controller's view as subview. – Asteroid Aug 26 '22 at 18:12
  • Seems confusing... have you designed a ***complex**** view in IB as a XIB (is that your `ReusableContainerview`?), and you want to programmatically add that view to a view controller's view? – DonMag Aug 26 '22 at 18:12
  • @Asteroid, how to initialize `reuseView ` in homevc programatically.. plz let me know – Swift Aug 26 '22 at 18:16
  • @DonMag, i have designed `ReusableContainerview` which is XIB uiview... but how to call ReusableContainerview in homevc programatically.. with out adding any view in home storyboard – Swift Aug 26 '22 at 18:19
  • In viewDidLoad() something like reuseView = ReusableContainerview(frame: CGRect(x: 0, y: 0, width: 100, height: 100)). Then you add it to the VC's view: self.view.addSubview(reuseView) – Asteroid Aug 26 '22 at 18:20
  • This might help: https://stackoverflow.com/a/29032601/4490923 – Asteroid Aug 26 '22 at 18:23

0 Answers0