Skip to content

Instantly share code, notes, and snippets.

@bwhiteley
Last active March 17, 2024 13:10
Show Gist options
  • Save bwhiteley/049e4bede49e71a6d2e2 to your computer and use it in GitHub Desktop.
Save bwhiteley/049e4bede49e71a6d2e2 to your computer and use it in GitHub Desktop.
Initialize Swift subclass of UIView, designed in .xib
// Create CustomView.xib, set File's Owner to CustomView.
// Link the top level view in the XIB to the contentView outlet.
class CustomView : UIView {
@IBOutlet private var contentView:UIView?
// other outlets
override init(frame: CGRect) { // for using CustomView in code
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
guard let content = contentView else { return }
content.frame = self.bounds
content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.addSubview(content)
}
}
@Abdulaziz1993
Copy link

thanks for the code

@sudebsm
Copy link

sudebsm commented Sep 26, 2018

Hi all
I need to send extra two parameters in CustomView class from the viewcontroller class , How this is possible.

@Bhide
Copy link

Bhide commented Jan 31, 2019

There's a memory leak shown at 'Bundle.main.loadNibNamed'

screen shot 2019-01-31 at 11 43 18 am

@maneesh888
Copy link

I think we are on the same page, I want to create a custom view with IBOutlets. And I want to create it in such a way that it can directly use in storyboard. But it seems to impossible, when init with coder initialise a view, the IBOutlets are nil. If I use a different method using files owner , awake from nib will never execute, here. The sad part is that, the dilemma is to just load a view to screen. Anyone have a comment?

@bhavik-98
Copy link

bhavik-98 commented Apr 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment