I have made a view that is in the story board and I want to add this view to the another view that is not in the story board and it has been created with codes here is my codes :
@IBOutlet weak var sideBarView: UIView!
var sideBarViews = UIView()
override func viewDidLoad()
{
super.viewDidLoad()
self.sideBarViews.frame = CGRect(x:UIScreen.main.bounds.width , y: 0, width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.height)
self.sideBarViews.backgroundColor = UIColor.init(red: 251/255, green: 251/255, blue: 251/255, alpha: 1.0)
UIApplication.shared.keyWindow!.addSubview(self.sideBarViews)
UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarViews)
self.view.bringSubview(toFront: self.sideBarViews)
}
@IBAction func sideBarMenu(_ sender: UIBarButtonItem)
{
UIView.animate(withDuration: 0.3, animations:
{
UIApplication.shared.keyWindow!.addSubview(self.sideBarViews)
UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarViews)
self.view.bringSubview(toFront: self.sideBarViews)
self.sideBarViews.frame = CGRect(x:UIScreen.main.bounds.width / 2 , y: 0, width: UIScreen.main.bounds.width / 2, height: UIScreen.main.bounds.height)
self.view.addSubview(self.sideBarView)
UIApplication.shared.keyWindow!.addSubview(self.sideBarView)
UIApplication.shared.keyWindow!.bringSubview(toFront: self.sideBarView)
self.view.bringSubview(toFront: self.sideBarView)
self.view.layoutIfNeeded()
})
}
The thing for UI components created in Storyboard inside a UIViewController
is that they are not reusable and not subclassable. Moreover, UIViewControllers
inside a specific storyboard can not be subclassed and reused later as other classes as well.
I suggest looking into creating a .xib
file with a dedicated UIView
subclass so you can reuse it anytime.
Here's a nice tutorial for that - https://medium.com/@brianclouser/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960