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
}
}
6
  • You first need to initialize reuseView and add it to the view controller's view as subview. Commented Aug 26, 2022 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? Commented Aug 26, 2022 at 18:12
  • @Asteroid, how to initialize reuseView in homevc programatically.. plz let me know Commented Aug 26, 2022 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 Commented Aug 26, 2022 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) Commented Aug 26, 2022 at 18:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.